2009-03-02 125 views
123

我编写了数据库模式(至今只有一个表),以及该表中的INSERT语句在一个文件中。然后,我创建了数据库,如下所示:转义SQLite查询中使用的单引号字符

$ sqlite3 newdatabase.db 
SQLite version 3.4.0 
Enter ".help" for instructions 
sqlite> .read ./schema.sql 
SQL error near line 16: near "s": syntax error 

线16我的文件看起来是这样的:

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there\'s'); 

的问题是一个单引号的转义字符。我还尝试了双引号转义(使用\\\'而不是\'),但那也不起作用。我究竟做错了什么?

回答

213

尝试单引号(许多数据库期望它的方式)增加了一倍,所以这将是:

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s'); 

相关报价从the documentation

字符串常量被封闭形成字符串用单引号(')。字符串中的单引号可以通过将两个单引号放在一行中进行编码 - 就像在Pascal中一样。不支持使用反斜杠字符的C样式转义,因为它们不是标准的SQL。 BLOB文字是包含十六进制数据的字符串文字,前面是单个“x”或“X”字符。 ...文字值也可以是标记“NULL”。

+5

另外,还要考虑使用绑定参数,如果主机语言支持它们(大多数情况下,但SQLite shell不支持)。然后,SQL将被插入到表名(field1,field2)VALUES(?,?)`中,并且这些值将直接提供(并且没有替换)。 – 2013-05-20 12:48:14

38

我相信你会希望通过加倍单引号逃脱:

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s'); 
0

在C#中,你可以使用下面的用双引号来代替单引号:

string sample = "St. Mary's"; 
string escapedSample = sample.Replace("'", "''"); 

而且输出将是:

"St. Mary''s" 

而且,如果你是工作用Sqlite直接;你可以用对象,而不是字符串的工作,赶上特殊的事情一样的DBNull:

private static string MySqlEscape(Object usString) 
{ 
    if (usString is DBNull) 
    { 
     return ""; 
    } 
    string sample = Convert.ToString(usString); 
    return sample.Replace("'", "''"); 
} 
1

以防万一,如果你有需要在数据库中插入一环或JSON字符串。尝试用单引号替换字符串。这是我的解决方案。例如,如果你有一个包含单引号的字符串。

String mystring = "Sample's"; 
String myfinalstring = mystring.replace("'","''"); 

String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')"; 

这个工作对我来说在C#和Java

0

在您的字符串替换所有('),使用

.replace(/\'/g,"''") 

例如:

sample = "St. Mary's and St. John's"; 
escapedSample = sample.replace(/\'/g,"''")