我希望能够在我的应用程序中将数据插入到sqlite数据库中,如果id存在,那么更新此行。
我完成了创建:
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
sqlite3_stmt *insertStmt = nil;
if(insertStmt == nil)
{
const char *insertSql = "INSERT INTO Category (id,name) VALUES(?,?)";
if(sqlite3_prepare_v2(database, insertSql, -1, &insertStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating insert statement. '%s'", sqlite3_errmsg(database));
}
sqlite3_bind_int(insertStmt, 1, 135);
sqlite3_bind_text(insertStmt, 2, [@"fds" UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(insertStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
//NSLog("Inserted");
//Reset the add statement.
sqlite3_reset(insertStmt);
insertStmt = nil;
}
sqlite3_close(database);
答案 0 :(得分:0)
使用OR REPLACE
限定符:
INSERT OR REPLACE INTO Category ...
这取决于是否存在仅包含id
列的UNIQUE约束(通常是主键)。
答案 1 :(得分:0)
您可以使用以下代码进行更新:
- (void)更新:(NSString *)查询{
sqlite3_stmt *statement=nil;
NSString *path = [self GetDatabasePath:DataBaseName] ;
if(sqlite3_open([path UTF8String],&databaseObj) == SQLITE_OK)
{
if(sqlite3_prepare_v2(databaseObj, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
sqlite3_step(statement);
}
sqlite3_finalize(statement);
}
if(sqlite3_close(databaseObj) == SQLITE_OK){
}else{
NSAssert1(0, @"Error: failed to close database on memwarning with message '%s'.", sqlite3_errmsg(databaseObj));
}
}