命令执行上的致命错误MySQL DB [英] Fatal error on command execution MySQL DB
本文介绍了命令执行上的致命错误MySQL DB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我有一个Windows窗体,其中有一个名为"txtSearch"的文本框.我想根据此文本框内的值检索数据.但是我收到错误执行命令时遇到致命错误".搜索结果应该在DataGridViewer上.
我的代码如下(删除了连接字符串):
Hi All,
I have a Windows form with a textbox named "txtSearch". I want to retrieve data based on value inside this textbox. However I get error "Fatal error encountered while executing command". The search result is supposed to be on a DataGridViewer.
My code is as below (Connection string is removed) :
try
{
dataGridView1.Visible = true;
BindingSource bs = new BindingSource();
DataTable newadm = new DataTable();
String term = txtSearch.Text;
string db = ----Connection String Goes Here----;
bs.DataSource = newadm;
this.dataGridView1.DataSource = bs;
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s = "select * from newadm where firstname like @term OR lastname like @term";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@term", MySqlDbType.VarChar, 40).Value = "%" + txtSearch.Text + "%";
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand(s, conn);
da.Fill(newadm);
da.Update(newadm);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
如果我删除具有实际值的占位符(@term),则效果很好.任何帮助将不胜感激.
在此先谢谢您.
If I remove the placeholders (@term), with an actual value, this works just fine. Any assitance will be greatly appreciated.
Thanks in advance.
推荐答案
您需要在字符串s中的@term周围加上单引号.
但是,我希望这不是真正的代码,因为您要将数据库暴露给SQL注入.
You need to put single quotes around @term in string s.
However, I hope this is not the real code because you are exposing the database to SQL injections.
替换代码
Replace the code
da.SelectCommand = cmd;
嗨Sandeep,
SQL命令可以直接在DB上正常运行.
如果删除占位符并提供实际值,该程序将正常运行.
仅对于占位符,命令执行失败.
ryanb31,您好,
我已经尝试过了,但是没有用.它返回空数据集.
Hi Sandeep,
The SQL commands are working perfectly on the DB directly.
If I remove the placeholders and give an actual value, the program works properly.
Only with placeholders, the command execution fails.
Hi ryanb31,
I have already tried it, but it does not work. It returns empty dataset.
这篇关于命令执行上的致命错误MySQL DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文