我有这样的代码,我需要从 Mysql
检索数据。如果我使用参数化查询,它不会采用实际参数值,而是采用参数名称作为值。
Error: @choise must be defined
MySqlConnection connection = new MySqlConnection("");
MySqlDataAdapter mySqlDataAdapter;
DataSet DS;
private string columnValue = xxx;
private string Choise = yyy;
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM table2 WHERE " + columnValue + " = @choise";
command.Parameters.Add(new MySqlParameter("@choise", Choise));
DS = new DataSet();
connection.Open();
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
mySqlDataAdapter.Fill(DS);
connection.Close();
当我运行这个时,我得到如下查询:
SELECT * FROM table2 WHERE xxx = @choise
而不是
从表 2 中选择 *,其中 xxx = yyy
。
哪里有问题?
我尝试过:
command.Parameters.Add(new MySqlParameter("@choise", Choise));
command.Parameters.AddWithValue("@choise", Choise);
当我使用实际变量而不是参数时,它工作得很好。
最佳答案
我认为您需要在添加参数之前在命令上运行 Prepare()
:
command.CommandText = "select * from table2 where " + columnValue + " = @choise";
command.Prepare();
command.Parameters.AddWithValue("@choise", Choise);
关于C# mysql 参数化查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22220190/