C# SQLite 使用 LIKE 参数化选择

发布于 2024-10-05 16:22:06 字数 364 浏览 0 评论 0原文

我正在尝试执行 SQL 查询,例如

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

This 在普通 SQL 中运行良好,但是当我在 C# 中使用 System.Data.SQLite 时,它​​仅适用于文字,而不是参数,例如

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

This 不返回任何结果。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅浅 2024-10-12 16:22:06

你不能那样做。参数必须是完整的值 - 它不仅仅是 SQL 中的字符串替换。你可以这样做:

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

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%");
波浪屿的海角声 2024-10-12 16:22:06

最简单的方法是使用“||”

使用:

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

代替:

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

我已经在此处回答

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文