C# SQLite Parameterized Select Using LIKE

2019-02-08 08:00发布

I am trying to do an SQL query such as

SELECT * FROM [TABLE] WHERE hostname LIKE '%myhostname%';

This works fine in plain SQL, but when I use System.Data.SQLite in C#, it only works with a literal, not a parameter, such as

string sel = "SELECT * FROM [TABLE] WHERE hostname LIKE '%@host%'";
...
command.Parameters.AddWithValue("@host", "myhostname");

This returns no results.

2条回答
我只想做你的唯一
2楼-- · 2019-02-08 09:03

Easiest way to do this is to use '||'

Use :

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

Instead Of:

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

I have already answered here

查看更多
Root(大扎)
3楼-- · 2019-02-08 09:04

You can't do that. The parameters must be complete values - it's not just a string substitution into the SQL. You could do this instead:

string sel = "SELECT * FROM [TABLE] WHERE hostname LIKE @host";
...
command.Parameters.AddWithValue("@host", "%myhostname%");
查看更多
登录 后发表回答