我有一个textbox
来过滤我SQL Database Table
的所有列。使用名为button
的{{1}}触发过滤。
FilterIDLS
保存解决方案时没有错误。但是当我调试它时,它指向了这个:
private void filterIDLS_Click_1(object sender, EventArgs e)
{
string txt = keyIDLS.Text;
if (txt != "")
{
_db.conn();
_db.cmd.CommandText = @"SELECT * FROM dbo.IncomingLog WHERE
[Date Received] LIKE '%{0}%' OR
[Reference Number] LIKE '%{0}%' OR
[Time Received] LIKE '%{0}%' OR
[Title/Description] LIKE '%{0}%' OR
[Received Copies] LIKE '%{0}%' OR
[Originating Office] LIKE '%{0}%' OR
[Received Person] LIKE '%{0}%' OR
[Filed Under] LIKE '%{0}%' OR
[Encoded By] LIKE '%{0}%'" + keyIDLS.Text;
dt = _db.executeDT();
}
else
{
MessageBox.Show("Please type a keyword to search!", "Nothing to Search", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (incomLogTableS.RowCount == 0)
{
MessageBox.Show("No records from the database found. Please try again.", "0 Records Found", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
并说SQLException未处理,并且在PRS'附近有不正确的语法。 (我在文本框中输入的关键字。)
我该怎么做才能解决这个问题?
答案 0 :(得分:1)
您已为字符串格式功能输入{0}占位符,但您从未调用string.Format(字符串,参数)来正确设置字符串格式。
_db.cmd.CommandText = string.Format(@"SELECT ......", keyIDLS.Text);
但是,在构建sql命令时,这种方法(string.Format)不正确。相反,您使用参数来避免Sql Injection并使用包含单引号的字符串解析问题。
_db.cmd.CommandText = @"SELECT * FROM dbo.IncomingLog WHERE
[Date Received] LIKE @p1 OR
[Reference Number] LIKE @p1 OR
[Time Received] LIKE @p1 OR
[Title/Description] LIKE @p1 OR
[Received Copies] LIKE @p1 OR
[Originating Office] LIKE @p1 OR
[Received Person] LIKE @p1 OR
[Filed Under] LIKE @p1 OR
[Encoded By] LIKE @p1"
List<SqlParameter> prms = new List<SqlParameter>()
{
new SqlParameter("@p1", SqlDbType.NVarChar) {Value = keyIDLS.Text}
};
dt = _db.executeDT(prms);
.....
public DataTable executeDT(List<SqlParameter> prms = null)
{
cmd.Connection = con;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable datatable = new DataTable("DataTable");
if(prms != null)
adapter.SelectCommand.Parameters.AddRange(prms.ToArray());
adapter.Fill(datatable);
return datatable;
}
我还要说明,只有当您的所有列都是NVarChar类型时,您的查询才能正常工作。许多字段似乎具有不同的数据类型,因此无法从使用相同值在DateTime,Numbers和Text字段中搜索的查询中获得有意义的结果。