SQLite3:数据库未保存

时间:2011-07-14 07:54:12

标签: database cocoa macos sqlite save

我正在创建一个Mac应用程序,它会将一些数据保存到SQLite数据库中。问题是:当我关闭数据库并再次打开它时,数据不存在。这是我的代码:

NSString *sql = [NSString stringWithFormat:@"INSERT INTO people(name, artist, id, album, location, cover) VALUES('%@', '%@', %d, '%@', '%@', '%@');", name, artist, ID, album, path, cover];

 sqlite3 *database = NULL;      
 sqlite3_open([[[NSBundle mainBundle] pathForResource:@"db" ofType:@"database"]
   cStringUsingEncoding:NSUTF8StringEncoding], &database);  

 sqlite3_stmt *statement;       
 sqlite3_prepare_v2(database, "CREATE TABLE IF NOT EXISTS people(name TEXT, id INT, artist TEXT, album TEXT, cover TEXT, location TEXT);", -1, &statement, NULL);   
 sqlite3_step(statement);
 sqlite3_finalize(statement);       
 sqlite3_prepare_v2(database, [sql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL);   
 sqlite3_step(statement);
 sqlite3_finalize(statement);

 statement = NULL;
 sqlite3_close(database);

1 个答案:

答案 0 :(得分:-1)

您可以使用此代码检查您的插入内容:

sqlite3_stmt *stmt;
char *errmsg;
const char *sql = [isql cStringUsingEncoding:NSUTF8StringEncoding];

if (sqlite3_prepare_v2(database, sql, -1, &stmt, NULL) != SQLITE_OK) {
    NSLog(@"SQL Warning: Erro ao executar a instrução '%s'.", sqlite3_errmsg(database));
    sqlite3_reset(stmt);
    sqlite3_finalize(stmt);
    return;
}

if(!sqlite3_exec(database, sql, nil, &stmt, &errmsg) == SQLITE_OK) NSLog(@"SQL Warning: '%s'.", sqlite3_errmsg(database));

sqlite3_reset(stmt);
sqlite3_finalize(stmt);