iPhone上INSERT的SQLite行为

iPhone上INSERT的SQLite行为,iphone,objective-c,sqlite,Iphone,Objective C,Sqlite,作为iPhone应用程序的一部分,我目前正在做以下工作 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSString *filePath = [documentsPath stringByAppendingPathComponent:@"citi

作为iPhone应用程序的一部分,我目前正在做以下工作

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:@"cities.sqlite"];

sqlite3 *database;

if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
   const char *sqlStatement = "insert into table (name, description, image) VALUES (?, ?, ?)";
   sqlite3_stmt *compiledStatement;
   if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)    {
      sqlite3_bind_text( compiledStatement, 1, [name UTF8String], -1, SQLITE_TRANSIENT);
      sqlite3_bind_text( compiledStatement, 2, [description UTF8String], -1, SQLITE_TRANSIENT);
      NSData *dataForImage = UIImagePNGRepresentation(image);
      sqlite3_bind_blob( compiledStatement, 3, [dataForImage bytes], [dataForImage length], SQLITE_TRANSIENT);

   }
   if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
      NSLog( @"Error: %s", sqlite3_errmsg(database) );
   } else {
      NSLog( @"Insert into row id = %d", sqlite3_last_insert_rowid(database));
   }
   sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
让我困惑的是如果我把那部分拿出来

   if(sqlite3_step(compiledStatement) != SQLITE_DONE ) {
      NSLog( @"Error: %s", sqlite3_errmsg(database) );
   } else {
      NSLog( @"Insert into row id = %d", sqlite3_last_insert_rowid(database));
   }

插入的内容未保存到数据库,因此丢失。我想我遗漏了一些明显的东西?

我完全建议使用包装器,而不是自己编译语句。。。这里有一个不错的选项列表:

当然不会插入。您需要调用sqlite3\u step来实际执行语句

退房

这是SQLITE的东西,不是iPhone特有的东西

从文件中:

在准备好一份声明之后 使用以下任一方法准备 sqlite3_prepare_v2()或 sqlite3_prepare16_v2()或 旧接口sqlite3_prepare()或 sqlite3_prepare16(),此函数 必须调用一次或多次以 评估该语句


这里只插入了一行,所以有很多样板代码。想想如果要插入多行,会发生什么情况:

  • 你仍然需要一份准备声明
  • 你还需要一份最终声明
  • 要添加的每一行都需要一个step语句。您可以将“步骤”视为“执行”(如果您正在查看SELECT语句,则可以将“获取下一行”)
顺便说一下,如果准备好的语句失败了,您可能不想“单步执行”

使用代码

const char *sqlStatement = "REPLACE INTO  table (name, description, image) VALUES (?, ?, ?)";

我不想“插入”

而是想知道你不使用核心数据的原因。我通常在SQLite周围使用一些包装器,或者现在更多的是核心数据。然而,我想知道如何直接使用这个库,所以……SQLite文档的布局不是很好。谢谢你的指点……但是是的,我遗漏了一些明显的东西。