2012-11-29 17 views
4

我有一个字符串,例如:似乎无法逃脱查询我发送到我的sqlite3的分贝,不知道为什么

string query; 
query = "insert or replace into TABLEA (a,b,c) values (@a,\"@b\",\"@c\");"; 

这样我可以插入串到B和C只是一个简单的替换:

string instring("I have a 3\" gauge"); 
string instring2("I am looking for 1/8\" thickness"); 
Replace(&query, "@a", to_string(1)); 
Replace(&query, "@b", instring); 
Replace(&query, "@c", instring2); 

所以现在我的查询字符串:

"insert or replace into TABLEA (a,b,c) values (1,\"I have a 3\" gauge\",\"I am looking for 1/8\" thickness\");"; 

SQLITE3得到它,它看起来像:

insert or replace into TABLEA (a,b,c) values (1,"I have a 3" gauge","I am looking for 1/8" thickness"); 

的问题是,串过早结束。我试图添加额外的转义字符,但这似乎也没有工作。

现在我使用sqlite3_exec()开展的一切。有什么我应该做的吗?准备好的声明是否处理了我想要做的事情?

我应该只是与prepared_v2尝试,并可能会解决问题?

我该如何接近这个?

+0

http://stackoverflow.com/questions/603572/how-to-properly-escape-a-single-quote- for-a-sqlite-database有助于理解我应该删除“我拥有,只是拥有”,然后搜索输入字符串'并插入额外的,这样DB语言就会明白' '是1的报价 – Fallenreaper

回答

3

在SQL中,字符串使用单引号,并且通过使用两个单引号被转义。 (双引号接受与MySQL的兼容性,但不应该被使用。)

您的查询应该是这样的:

INSERT OR REPLACE INTO TableA(a, b, c) 
VALUES (1, 'I have a 3" gauge', 'I am looking for 3/8" thickness') 

或像这样:

INSERT OR REPLACE INTO TableA(a, b, c) 
VALUES (1, "I have a 3"" gauge", "I am looking for 3/8"" thickness") 

然而,为了避免字符串格式化问题,建议使用参数。 这是怎么回事,直接SQLite的函数调用作品(包装可能会有所改变):

const char *sql = "INSERT OR REPLACE INTO TableA(a, b, c) VALUES (1, ?, ?)"; 
sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); 
sqlite3_bind_text(stmt, 1, "I have a 3\" gauge", -1, SQLITE_TRANSIENT); 
sqlite3_bind_text(stmt, 2, "I am looking for 3/8\" thickness", -1, SQLITE_TRANSIENT); 
+0

谢谢CL,它帮助了很多 – Fallenreaper

2

您需要周围的每个内部串单引号:

string query; 
query = "insert or replace into TABLEA (a,b,c) values (@a,'\"@b\"','\"@c\"');"; 
+1

是否必须围绕整个内部字符串?或者它可以像......'\“@ b \'','\”@ c \“');”;围绕单个组件? – Fallenreaper

+0

你在想什么?我不确定我是否应该单独引用单引号而不是双引号。 – Fallenreaper

+0

我试图把它包装到整个事物中,并且它会调用一个错误,说明3个列或2个条目是什么,所以它会将整个单引号字符串识别为1个条目。此外,字符串可以有一个单引号,当我测试它时,它会在\'上发生错误,因为它仍然认出'作为字符串的结尾。 – Fallenreaper

相关问题