如何在C#中的变量中保存SQL"Select"结果

Luc*_*cas 1 c# mysql sql

我正在使用连接到MySQL的Visual C#进行学习,当他输入已存在的用户名时,我不得不向用户抛出错误.

将事物放入数据库的当前代码(可能没用,一旦我的问题可能更多关于SQL):

s = new sql(); // This calls a class that works as an adapter to connect form with the database
Conn = s.Connection;
Conn.Open();
coma = Conn.CreateCommand();
coma.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES ('"+username.Text+"','"+password.Text+"');";
Run Code Online (Sandbox Code Playgroud)

coma.ExecuteNonQuery();

我想要做的是将"username.Text"("username"是一个TextBox)与数据库的"test"表上的值进行比较,如果某些值匹配,则调用MessageBox.Show("嘿家伙,这个用户名已经是在使用中!尝试不同的东西)

Ant*_*ram 5

关于代码示例的一些要点

  1. 您希望确保处置连接和命令对象.对于我的回答,我已经将它们包装在using可以为我处理的陈述中.
  2. 您不希望使用未经过输入的输入转到数据库.我将在示例中使用参数化查询.
  3. 以纯文本格式存储密码不是一个好主意.我不打算演示更安全的技术,只知道查找加密密码,盐键等信息.

而现在是一些代码.在这里,我正在使用OleDb对象,对您的特定数据库进行改造.当然,为表格,列等提供适当的名称.

using (OleDbConnection connection = SomeMethodReturningConnection())
using (OleDbCommand command = SomeMethodReturningCommand())
{
    command.Parameters.Add(new OleDbParameter("@username", username));
    command.CommandText = "Select Count(*) From Users where Username = @username";
    connection.Open();
    int output = (int)command.ExecuteScalar();

    if (output > 0)
    {
        // username already exists, provide appropriate action
    }
    else
    {
        // perform insert 
        // note: @username parameter already exists, do not need to add again
        command.Parameters.Add(new OleDbParameter("@password", password));
        command.CommandText = "Insert Into Users (Username, Password) Values (@username, @password)";
        command.ExecuteNonQuery();
    }
}
Run Code Online (Sandbox Code Playgroud)