sql ce escape '(单引号) C#
我正在编写一些代码来将名称存储在数据库中。我将名字限制为仅某些字符,但姓氏是一个挑战。由于有些人的名字中有单引号(例如 O'Brian),我需要允许这样做。所以我编写了一个正则表达式替换来将 ' 替换为 \',我认为这应该使 ' 成为文字。就替换而言,它有效,但它仍然标记字符串的结尾,并且我收到错误
解析查询时出错。 [ 令牌行号 = 1,令牌行偏移 = 71,错误中的令牌 = Brian]
我理解该错误,单引号标记要输入的字符串的结尾,将字符串的其余部分 Brian 放在引号之外。
我正在使用的代码:
Regex reg = new Regex("\'");
firstName = reg.Replace(firstName, "\\'");
lastName = reg.Replace(lastName, "\\'"):
然后使用 string.format 构建选择查询
sqlInsertObj.CommandText = string.Format("INSERT INTO childNameId (childFName, childLName) VALUES ('{0}', '{1}')", fName, lName);
sqlInsertObj.ExecuteNonQuery();
这适用于任何条目,除非名称中有引号。
I am writing some code to store names in a database. I limit the names to only certain characters, but last names are a challenge. Since some people have single quotes in their name (example O'Brian) I need to allow this. So I wrote a regex replace to replace the ' with a \' which I assumed should make the ' a literal. It works as far as replacement goes, but it still marks the end of the string, and I get the error
There was an error parsing the query. [ Token line number=1, token line offeset = 71, token in error=Brian]
I understand the error, the single quote marks the end of the string to be entered leaving the rest of the string Brian outside the quotes.
The code I am using:
Regex reg = new Regex("\'");
firstName = reg.Replace(firstName, "\\'");
lastName = reg.Replace(lastName, "\\'"):
Then the select query is built with string.format
sqlInsertObj.CommandText = string.Format("INSERT INTO childNameId (childFName, childLName) VALUES ('{0}', '{1}')", fName, lName);
sqlInsertObj.ExecuteNonQuery();
This works for any entry, except when there is a quote in the name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最好使用参数化 SQL 查询,而不是使用字符串连接来构建它们。文档和示例可以在 MSDN。
如果您坚持字符串连接,请使用双单引号而不是 \ 对其进行转义。
It's better to use parameterized sql queries, instead of building them with string concatenation. Documentation and an example can be found at MSDN.
If you insist on string concatenation escape it with a double single quote instead of \.