如何在SQLite查询中使用带有参数的Like运算符?

时间:2015-01-22 22:59:48

标签: c# sqlite sql-injection sql-like query-parameters

我可以通过在LINQPad中输入它来获得我期望的结果:

SELECT * FROM WorkTable WHERE WTName LIKE "DSD__20090410014953000%"

(它显示了WTName值为DSD__20090410014953000.xml的记录“)

但尝试以编程方式执行此操作正在尝试。我试过了:

const string qry = "SELECT SiteNum FROM WorkTable WHERE WTName LIKE @wtName%";
using (SQLiteConnection con = new SQLiteConnection(HHSUtils.GetDBConnection()))
{
    con.Open();
    SQLiteCommand cmd = new SQLiteCommand(qry, con);
    cmd.Parameters.Add(new SQLiteParameter("wtName", tableName));
    siteNum = Convert.ToInt32(cmd.ExecuteScalar());
}

...但它会导致应用崩溃,我的日志文件会告诉我原因:

Message: From application-wide exception handler: System.Data.SQLite.SQLiteException: SQL logic error or missing database
near "%": syntax error

所以也许它认为查询参数名为“wtName%”而不是“wtName”;但是将参数和“what”opertor(“%”)与空格分开也不起作用。

我可以通过将查询参数嵌入到字符串中来实现retro / kludgy,如下所示:

const string qry = String.Format("SELECT SiteNum FROM WorkTable WHERE WTName LIKE {0}%", tableName);

...并且完全不使用查询参数,但我担心如果我这样做Troy Hunt会出现在我的房子里并用栏杆鞭打我,同时辱骂SQL注入。

如何获取数据并同时编写安全代码?

3 个答案:

答案 0 :(得分:8)

应将通配符%添加到参数值,而不是参数名称

const string qry = "SELECT SiteNum FROM WorkTable WHERE WTName LIKE @wtName";
using (SQLiteConnection con = new SQLiteConnection(HHSUtils.GetDBConnection()))
{
    con.Open();
    SQLiteCommand cmd = new SQLiteCommand(qry, con);
    cmd.Parameters.Add(new SQLiteParameter("@wtName", tableName + "%"));
    siteNum = Convert.ToInt32(cmd.ExecuteScalar());
}

而且,我不确定这里是否重要,但通常我会插入参数名称以及占位符中使用的确切名称(@wtName)

答案 1 :(得分:5)

最简单的方法是使用' ||'

使用:

const string qry = "SELECT SiteNum FROM WorkTable WHERE WTName LIKE @wtName || '%' ";

代替:

const string qry = "SELECT SiteNum FROM WorkTable WHERE WTName LIKE @wtName%";

答案 2 :(得分:-1)

尝试定义这样的查询:

const string qry = "SELECT SiteNum FROM WorkTable WHERE WTName LIKE @wtName + '%'";