<分区>
我有 UITextView 用于写笔记。写完笔记然后单击完成按钮文本将保存到数据库。在我添加更多文本后,从旧文本继续,然后单击完成按钮,它会保存新的文本行。
表:
texts texts_id
Hi 1
Hi, How are u? 1
首先,我写了 Hi 文本,然后单击完成。然后我从数据库中查询文本并写下你好吗?但它保存了新行?我需要用 Hi 替换第一行,你好吗?可能吗?
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
const char *sql = [[NSString stringWithFormat:@"SELECT textnotes FROM textnote where textnote = '%@','%@',",txtview.text,artID] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(@"sql is %s",sql);
BOOL favExist = false;
sqlite3_stmt *statement, *addStmt;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// We "step" through the results - once for each row.
while (sqlite3_step(statement) == SQLITE_ROW) {
favExist = true;
}
}
if(!favExist){
const char *sqlInsert = [[NSString stringWithFormat:@"insert into textnote (textnotes,text_id ) values ('%@','%@')", txtview.text,artID] cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(@"sql insert is %s",sqlInsert);
// [catID release];
if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) != SQLITE_OK)
NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
if(SQLITE_DONE != sqlite3_step(addStmt))
NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
}
最佳答案
您应该执行“UPDATE”语句,而不是插入。
在第一次“完成”点击时,您的代码没有问题,但在随后点击“完成”按钮时,您需要更新行,您需要使用类似这样的东西。
const char *sqlUpdate = [[NSString stringWithFormat:@"update textnotes set text = '%@' where id = rowID", txtview.text,rowID] cStringUsingEncoding:NSUTF8StringEncoding];
我希望这对你有意义。插入时,您只是添加一个新行。看起来您的“id”列也不是 AutoIncrement,因为它应该是这样行 ID 才不会重复。
关于ios - 如何在 iOS 中更新保存到数据库的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19679497/