2012-11-29 16 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

相關問題