Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于SQLite查询的转义单引号字符_Sqlite_Escaping - Fatal编程技术网

用于SQLite查询的转义单引号字符

用于SQLite查询的转义单引号字符,sqlite,escaping,Sqlite,Escaping,我在一个文件中编写了数据库模式(到目前为止只有一个表)和该表的INSERT语句。然后,我创建了数据库,如下所示: $ 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

我在一个文件中编写了数据库模式(到目前为止只有一个表)和该表的INSERT语句。然后,我创建了数据库,如下所示:

$ 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');

问题是单引号的转义字符。我还尝试了对单引号进行双转义(使用
\\'
而不是
\'
),但也没有成功。我做错了什么?

尝试将单引号加倍(许多数据库都这样认为),因此:

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');
相关报价来自:

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


我相信你会想通过将单引号加倍来逃避:

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');
在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("'", "''");
}

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

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

 String query = "INSERT INTO "+table name+" ("+field1+") values ('"+myfinalstring+"')";
这在c#和java中适用于我

要替换字符串中的所有('),请使用

.replace(/\'/g,"''")
例如:

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

在bash脚本中,我发现对于可能为null或包含需要转义的字符(如连字符)的值,必须在值周围转义双引号

在本例中,columnA的值可以为null或包含连字符:

sqlite3$db\u name“插入到foo值中(\“$columnA\”,$columnB)”;

也可以考虑,如果宿主语言支持绑定参数(大多数都是,但是SQLite shell不支持)。然后SQL将
插入表名(field1,field2)的值(?,)
中,这些值将直接提供(并且不替换)。我们不能只使用双引号吗?比如:在表_name(field1,field2)中插入值(123,“Hello there's”)?此外,根据字符串的生存期,第一步可能是将“”转换为“”,然后再将其加倍。@JacksOnF1re在SQL中,双引号用于标识符而不是字符串。如
插入“表_名称”(“字段1”、“字段2”)值(“值1”、“值2”)这是一个兼容性的怪癖,双引号就像文字一样工作。参见:注:替换C#中的(“”,“”)。(唯一的变化是大写字母R。)sqlite中的双引号表示“这是一个标识符,而不是一个字符串。”因此,尽管这对于一些黑客来说是可以接受的,但您不希望在生产中使用它。