MySQL 的“like”查询问题和混乱

发布于 2024-10-16 10:33:40 字数 332 浏览 7 评论 0原文

我需要使用字符串查询来对与 MySQL 服务器交互的 C# 程序进行数据库搜索。我想要找到的是一个与我的其他变量之一“类似”的名称 (nameVar)

我在 C# 程序中有以下查询

string q = "SELECT * 
              FROM TABLE 
             WHERE name is like %?nameVar%";

一旦在我的程序中执行查询,我就会收到一个语法错误,告诉我语法接近 “喜欢”是不正确的。一旦我删除“%”符号,它就可以正常工作。

我很困惑,在构建查询字符串时是否必须删除 % 符号?

I need to use a string query to make a DB search for a C# program that interacts with MySQL server. What I want to find is a name that is 'like' one of my other variables (nameVar)

I have the following query in a C# program

string q = "SELECT * 
              FROM TABLE 
             WHERE name is like %?nameVar%";

As soon as execute the query in my program I get a syntax error telling me that syntax near
'like' is incorrect. As soon as I remove the "%" sign, it works fine.

I am confused, is mandatory to remove the % sign while building a query string?

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

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

发布评论

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

评论(5

最佳男配角 2024-10-23 10:33:40

您的参数正在替换 ?nameVar 部分,包括引号。如果参数是“TEST”,您的查询将显示为

string q = "SELECT * 
              FROM TABLE 
             WHERE name is like %'TEST'%";

如您所见,% 符号不合适。将它们从 C# 程序包含到 namevar 中,或者将查询更改为

string q = "SELECT * 
              FROM TABLE 
             WHERE name is like '%' + ?nameVar + '%'";

Your parameter is replacing the ?nameVar part, including quotes. If the param is "TEST", your query gets presented as

string q = "SELECT * 
              FROM TABLE 
             WHERE name is like %'TEST'%";

As you can see, the % signs are out of place. either include them from the C# program into namevar, or change the query to

string q = "SELECT * 
              FROM TABLE 
             WHERE name is like '%' + ?nameVar + '%'";
ˇ宁静的妩媚 2024-10-23 10:33:40

您需要引用查询:

string q = "SELECT * from table where name is like '%?nameVar%'";

you need to quote the query:

string q = "SELECT * from table where name is like '%?nameVar%'";
櫻之舞 2024-10-23 10:33:40

SQL 中的字符串需要用单引号引起来:

string q = "SELECT * 
              FROM TABLE 
             WHERE name LIKE '%?nameVar%' ";

此外,使用 LIKE 时没有 IS 运算符。

Strings in SQL need to be enclosed in single quotes:

string q = "SELECT * 
              FROM TABLE 
             WHERE name LIKE '%?nameVar%' ";

Also, there's no IS operator when using LIKE.

虫児飞 2024-10-23 10:33:40

我认为正确的语法是:

SELECT * FROM table WHERE fields LIKE '%phrase%'

I think the correct syntax is:

SELECT * FROM table WHERE fields LIKE '%phrase%'
三生殊途 2024-10-23 10:33:40

我认为你必须省略“是”。

MySQL 模式匹配

I think you have to leave out 'is'.

MySQL Pattern Matching

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