C#Mysql选择文本框文本

时间:2014-04-16 10:27:21

标签: c# mysql select

我试图使用文本框的文本在mysql数据库中选择一行。 但是,当我使用以下代码时,我收到错误。

        MySqlCommand command = connection.CreateCommand(); //we create a command
        command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ;  //in commandtext, we write the Query
        MySqlDataReader reader = command.ExecuteReader();  //execute the SELECT command, which returns the data into the reader

        while (reader.Read())  //while there is data to read
        {
            MessageBox.Show(reader["info"].ToString());
        }

它适用于字母,但当我尝试使用问号或类似的东西时,我会收到以下错误:

"参数'?'必须定义。"

2 个答案:

答案 0 :(得分:1)

而不是

command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ;

使用此

command.CommandText = "SELECT * FROM info where id=@id";
command.Parameters.AddWithValue("@id",textBox1.Text);

答案 1 :(得分:0)

在这种情况下你最好使用参数

command.CommandText = "SELECT * FROM info where id=@id"; 

然后你需要设置参数值

command.Parameters.AddWithValue(@id, textBox1.Text);

完整代码:

   string queryString="SELECT * FROM info where id=@id";
   using (MySqlConnection connection = new MySqlConnection(connectionString))
   using (MySqlCommand command = new MySqlCommand(queryString, connection))
   {
        connection.Open();
        command.Parameters.AddWithValue("@id", textBox1.Text);
        using (MySqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // do something ...
            }
        }
    }

更新:

更改参数值设置行,如下所示

 command.Parameters.AddWithValue("@id", textBox1.Text);