- 使用参数,不要用字符串格式化你的更新语句
- 添加大量跟踪,检查返回代码并检查错误代码(你的问题是不清楚什么错误,你在 iPhone 上遇到的问题)。
- 使用 sqlite3_errmsg 获取错误消息
- 构建您的 dbPath 并将其注销。确保您可以从模拟器下的终端打开数据库。请记住,sqlite 将被动地在内存中创建一个数据库,因此如果您的路径已关闭并且数据库不存在,它可能会令人困惑。
- 打印出您的更新语句并在您登录的路径中从终端中的 sqlite cmdline 应用程序尝试它。
- 如果您将数据库放在主捆绑资源中,它是一个模板,需要复制才能打开并写入它。
这是我的示例中的更新功能:
- (void)updateContact: (Contact*)contact error:(NSError**)error
{
if (![self ensureDatabaseOpen:error])
{
return;
}
NSLog(@">> ContactManager::updateContact");
// prep statement
sqlite3_stmt *statement;
NSString *querySQL = @"update contacts set name=?,address=?,phone=? where id=?";
NSLog(@"query: %@", querySQL);
const char *query_stmt = [querySQL UTF8String];
// preparing a query compiles the query so it can be re-used.
sqlite3_prepare_v2(_contactDb, query_stmt, -1, &statement, NULL);
sqlite3_bind_text(statement, 1, [[contact name] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(statement, 2, [[contact address] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_text(statement, 3, [[contact phone] UTF8String], -1, SQLITE_STATIC);
sqlite3_bind_int64(statement, 4, [[contact id] longLongValue]);
NSLog(@"bind name: %@", [contact name]);
NSLog(@"bind address: %@", [contact address]);
NSLog(@"bind phone: %@", [contact phone]);
NSLog(@"bind int64: %qi", [[contact id] longLongValue]);
// process result
if (sqlite3_step(statement) != SQLITE_DONE)
{
NSLog(@"error: %s", sqlite3_errmsg(_contactDb));
}
sqlite3_finalize(statement);
}
在示例中,数据库从资源复制到路径并打开。这是我用来执行此操作的确保打开功能:
- (BOOL)ensureDatabaseOpen: (NSError **)error
{
// already created db connection
if (_contactDb != nil)
{
return YES;
}
NSLog(@">> ContactManager::ensureDatabaseOpen");
if (![self ensureDatabasePrepared:error])
{
return NO;
}
const char *dbpath = [_dbPath UTF8String];
if (sqlite3_open(dbpath, &_contactDb) != SQLITE_OK &&
error != nil)
{
*error = [[[NSError alloc] initWithDomain:@"ContactsManager" code:1000 userInfo:nil] autorelease];
return NO;
}
NSLog(@"opened");
return YES;
}
- (BOOL)ensureDatabasePrepared: (NSError **)error
{
// already prepared
if ((_dbPath != nil) &&
([[NSFileManager defaultManager] fileExistsAtPath:_dbPath]))
{
return YES;
}
// db in main bundle - cant edit. copy to library if !exist
NSString *dbTemplatePath = [[NSBundle mainBundle] pathForResource:@"contacts" ofType:@"db"];
NSLog(@"%@", dbTemplatePath);
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject];
_dbPath = [libraryPath stringByAppendingPathComponent:@"contacts.db"];
NSLog(@"dbPath: %@", _dbPath);
// copy db from template to library
if (![[NSFileManager defaultManager] fileExistsAtPath:_dbPath])
{
NSLog(@"db not exists");
NSError *error = nil;
if (![[NSFileManager defaultManager] copyItemAtPath:dbTemplatePath toPath:_dbPath error:&error])
{
return NO;
}
NSLog(@"copied");
}
return YES;
}