2017-02-17 58 views
0

我一直在尋找一些類似的問題在這裏,但似乎無法找到任何工作解決方案。不能發送包含撇號的用戶輸入到sqlite3數據庫(Obj-C)

我的應用程序允許用戶在UITextField中編寫他們想要的任何內容並將其發送到sqlite3數據庫。但是,如果它包含一個撇號,它將不會發送它。

我知道把兩個撇號放在文本字段的作品中,但這根本不方便用戶......任何想法?

謝謝!

- (IBAction)saveInfo:(id)sender { 
    // Prepare the query string. 
    // If the recordIDToEdit property has value other than -1, then create an update query. Otherwise create an insert query. 
    NSString *query; 
    if (self.recordIDToEdit == -1) { 
     query = [NSString stringWithFormat:@"insert into peopleInfo values(null, '%@', %@)", self.txtFirstname.text, self.txtDate.text]; 
    } 
    else{ 
     query = [NSString stringWithFormat:@"update peopleInfo set firstname='%@', date=%@ where peopleInfoID=%d", self.txtFirstname.text, self.txtDate.text, self.recordIDToEdit]; 
    } 
+0

它對我來說很危險。你在iOS中創建一個SQLite客戶端? – Raptor

+0

這只是爲了練習,但它爲什麼危險? – Cuckoo

+0

由於小鮑比表,請參閱下面的答案。 –

回答

1

千萬不要這樣做!永遠記住小鮑比表: Exploits of a Mom

使用prepared statements插入數據到數據庫,從不連接/建立你自己的語句;看看這裏:

Objective-C: Fast SQLite Inserts with Prepared Statements for Escaped Apostrophes and SQL Injection Protection


在你自己的風險,你可以使用stringByReplacingOccurrencesOfString:withString:逃脫每個單引號用兩個單引號:

NSString *firstName = self.txtFirstname.text; 
firstName = [firstName stringByReplacingOccurrencesOfString:@"'" withString:@"''"]; 

if (self.recordIDToEdit == -1) { 
    query = [NSString stringWithFormat:@"insert into peopleInfo values(null, '%@', %@)", firstName, self.txtDate.text]; 
} 
else{ 
    query = [NSString stringWithFormat:@"update peopleInfo set firstname='%@', date=%@ where peopleInfoID=%d", firstName, self.txtDate.text, self.recordIDToEdit]; 
} 
+0

查看上面的答案,使用'stringByReplacingOccurrencesOfString:withString:' –

0

你應該總是做一些連接查詢時的一種「字符串轉義」。至於安全性,請查找SQL注入攻擊。

+0

我明白了,感謝您的信息! – Cuckoo

+0

不客氣。 Upvote我的答案,如果它有幫助。謝謝 :) –

相關問題