C#Mysql选择文本框文本
本文关键字:文本 选择 C#Mysql | 更新日期: 2023-09-27 17:58:30
我试图使用文本框的文本在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());
}
它适用于字母,但当我试图使用问号或类似的东西时,我会出现以下错误:
"必须定义参数‘?’。"
而不是
command.CommandText = "SELECT * FROM info where id=" + textBox1.Text ;
使用此
command.CommandText = "SELECT * FROM info where id=@id";
command.Parameters.AddWithValue("@id",textBox1.Text);
在这种情况下,您最好使用参数
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);