无法从 SQL 表中读取包含反斜杠的字符串
我正在尝试从 sql 表中读取一个包含反斜杠的字符串。由于某种原因,我无法在字符串中传递反斜杠。 我的字符串是用户名,其格式如下:域\用户名 我将其发送到表中,如下所示:
SqlCommand scomm = new SqlCommand();
SqlDataReader sr;
string nameOfUser = "Domain\userName";
scomm.CommandText = "SELECT * FROM tableOfUsers WHERE UserName=" + nameOfUser;
sr = scomm.ExecuteReader();
在调试期间,我可以看到添加了另一个反斜杠作为转义字符,但是我不知道 sql 部分会发生什么以及为什么会引发异常。我尝试使用@,但这也没有帮助。 如果您能为我提供任何帮助,我将不胜感激。
I am trying to read a string that includes a backslash in it from a sql table. For some reason I can not pass the back slash within the string.
My string is the user name and its in this format: Domain\username
I send it to the table as so:
SqlCommand scomm = new SqlCommand();
SqlDataReader sr;
string nameOfUser = "Domain\userName";
scomm.CommandText = "SELECT * FROM tableOfUsers WHERE UserName=" + nameOfUser;
sr = scomm.ExecuteReader();
During the debug I can see that another backslash is added as an escape character however I don't know what happens with the sql part and why an exception is thrown. I tried using @ but that didn't help either.
I would appreciate any help you can provide me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
SqlParameter
。Use
SqlParameter
.您可以使用字符串文字
或转义反斜杠
您的查询也有一些错误。理论上,您需要在 nameOfUser 周围加上引号
,但是您应该确实使用参数化查询,
这将保护您免受 的影响Sql 注入攻击,更常见的是,将允许您的查询适用于名字带有
'
的人(例如“O'Reilly”)You can use a string literal
or escape your backslash
Your query also has some errors in it. You theoretically need to put quotes around nameOfUser
But you should really use a parameterized query
This will protect your against Sql Injection attacks, and, more mundanely, will allow your query to work with people whose names have a
'
—like "O'Reilly"使用 SqlParameter。Sql 参数文档。因为 SqlPrameter 类将提供避免 Sql 注入和其他问题的功能,这是数据库不允许的。
Use SqlParameter.Sql Parameter Documentation. as the SqlPrameter Class will provide the functionality to avoid Sql Injections and other issues, which db not allowed.