简体   繁体   English

sql ce escape'(单引号)C#

[英]sql ce escape '(single quote) C#

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. 由于有些人的名字中有单引号(例如O'Brian),我需要允许这样做。 So I wrote a regex replace to replace the ' with a \\' which I assumed should make the ' a literal. 所以我写了一个正则表达式替换来替换'with a',我认为应该使'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] [令牌行号= 1,令牌行offeset = 71,令牌错误= 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. 我理解错误,单引号标记要输入的字符串的结尾,留下引号之外的其余字符串Brian。

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 然后使用string.format构建select查询

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. 这适用于任何条目,除非名称中有引号。

It's better to use parameterized sql queries, instead of building them with string concatenation. 最好使用参数化的sql查询,而不是使用字符串连接来构建它们。 Documentation and an example can be found at MSDN . 可以在MSDN上找到文档和示例。

If you insist on string concatenation escape it with a double single quote instead of \\. 如果你坚持使用字符串连接,则使用双引号而不是\\来转义它。

firstName = firstName.Replace("'", "''" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM