2015-06-09 31 views
0

我在sqlite數據庫插入一些數據,它工作正常,但我注意到,我不能插入字包含字符",是?它的一個常見問題我應該改變分析文本和編輯每"角色,我覺得不能插入「字符到Sqlite數據庫[Objective-C]

這是我使用,以便將數據插入到我的數據庫代碼:

UICollectionViewCell *cell = (UICollectionViewCell *)button.superview.superview; 
     NSIndexPath *indexPath = [self.customCollectionView indexPathForCell:cell]; 
     FolderProducts *item = _feedItems[indexPath.item]; 

     sqlite3_stmt *statement; 
     const char *dbpath = [databasePath UTF8String]; 

     if (sqlite3_open(dbpath, &Carrello) == SQLITE_OK) 
     { 
      NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CarrelloMese (titolo, codice, prezzo, urlImg) VALUES (\"%@\", \"%@\", \"%@\", \"%@\")",item.nomeProdotto, item.codice, item.prezzo, item.urlImg]; 

      const char *insert_stmt = [insertSQL UTF8String]; 

      sqlite3_prepare_v2(Carrello, insert_stmt, -1, &statement, NULL); 

      if (sqlite3_step(statement) == SQLITE_DONE) 
      { 

      } else { 

      } 

      sqlite3_finalize(statement); 
      sqlite3_close(Carrello); 
     } 
+1

綁定變量的準備發言;這就是它的目的。 – Droppy

+0

@Droppy你能解釋一下嗎? – Signo

+0

已準備好的語句旨在讓您可以準備一次語句,並在執行準備好的語句多次時將不同的值綁定到佔位符。這個綁定過程將處理轉義的特殊字符,這是你的情況。 – Droppy

回答

2

您需要綁定您的SQLite語句使用sqlite3_bind_xxx()功能。基本上,你從你的語句中刪除所有的變量(在你的情況下是%@)並用'?'替換它們。 SQLite然後知道在哪裏?必須是一個變量,因此不會混淆命令。

例如,假設你想綁定單詞「INSERT」。使用? SQLite不會將其作爲命令讀取,然後標記錯誤。

閱讀文檔(上面的鏈接)瞭解如何使用綁定函數的完整信息。

這裏是你的代碼可能會是什麼樣結合(未經測試):

sqlite3_stmt *statement; 
     const char *dbpath = [databasePath UTF8String]; 

     if (sqlite3_open(dbpath, &Carrello) == SQLITE_OK) 
     { 
      NSString *insertSQL = [NSString stringWithFormat: @"INSERT INTO CarrelloMese (titolo, codice, prezzo, urlImg) VALUES (?,?,?,?)"]; 

      const char *insert_stmt = [insertSQL UTF8String]; 

      sqlite3_prepare_v2(Carrello, insert_stmt, -1, &statement, NULL); 

      if (sqlite3_bind_text(statement, 0, item.nomeProdotto.UTF8String, item.nomeProdotto.length, SQLITE_STATIC) != SQLITE_OK) { 
       NSLog(@"An error occurred"); 
      } 
      // Etc etc 
      // SQLite bind works like this: sqlite_bind_text/int/e.t.c(sqlite3_stmt,index_of_variable, value); 
      // there are optionally parameters for text length and copy type SQLITE_STATIC and SQLITE_TRANSIENT. 

      if (sqlite3_step(statement) == SQLITE_DONE) 
      { 

      } else { 

      } 

      sqlite3_finalize(statement); 
      sqlite3_close(Carrello); 
     } 
+0

不是最好的編碼示例。 'insertSQL' /'insert_stmt'發生了什麼?錯誤檢查和報告也缺乏。而且,每次運行語句時,您都不應該鼓勵打開/關閉數據庫。 – Droppy

+1

我複製並粘貼了他的代碼,然後添加了一個sqlite_bind_xxx()函數作爲示例。我同意代碼可以改進(我個人不會打擾NSStrings,只是直接用char *),但我覺得這超出了問題的範圍。 –

+0

只是一個錯字,它的sqlite3_bind_text, Ty的幫助! – Signo