我需要从Mysql
检索数据的代码。如果我使用参数化查询,它不会采用实际参数值,而是将参数名称作为值。
错误:必须定义@choise
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
而不是
SELECT * FROM table2 WHERE xxx = yyy
。
问题出在哪儿?
我试过了:
command.Parameters.Add(new MySqlParameter("@choise", Choise));
command.Parameters.AddWithValue("@choise", Choise);
当我使用实际变量而不是参数时,它工作正常。
答案 0 :(得分:0)
我认为在添加参数之前需要在命令上运行Prepare()
:
command.CommandText = "select * from table2 where " + columnValue + " = @choise";
command.Prepare();
command.Parameters.AddWithValue("@choise", Choise);
答案 1 :(得分:0)
请改为尝试:
command.CommandText = "SELECT * FROM `table2` WHERE `" + columnValue + "` = @choise";
command.Parameters.AddWithValue("@choise", Choise);