不能插入“字符到Sqlite数据库[Objective-C]

问题描述:

我在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

您需要绑定您的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