在sqlite中更新语句

时间:2010-07-20 12:44:15

标签: sqlite

嘿我想要做的是在字段存在时更新表格或插入用户指定的新值。

为此,我要做的是选择表中的所有内容,并检查用户输入的名称是否存在,否则将其更新或插入。

但问题是当表中没有数据时查询失败并且表中没有插入数据。

NSString *query = @"select * from PPM";
sqlite_stmt *statement;

if(sqlite_prepare_v2(database,[query UTF8string],-1,&statement,NULL) == SQLITE_OK)
{
    while (sqlite3_step(statement) == SQLITE_ROW)
     //select data from table  
     //if value entered is same as entered by user update the table
     //else insert in the table
}

2 个答案:

答案 0 :(得分:3)

INSERT OR REPLACE怎么样? 您可以将它与数据库结构中的UNIQUE约束一起使用,以替换已存在的值,如果值已经存在,则将其插入。

shell> sqlite3
SQLite version 3.6.23
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> CREATE TABLE user(name UNIQUE, value);
sqlite> INSERT OR REPLACE INTO user VALUES("foo", 123);
sqlite> SELECT * FROM user;
foo|123
sqlite> INSERT OR REPLACE INTO user VALUES("foo", 321);
sqlite> SELECT * FROM user;
foo|321

答案 1 :(得分:1)

如果使用INSERT命令的INSERT OR REPLACE变体,则不需要检查现有数据,因为只要存在具有UNIQUE约束的列,SQLite就会为您执行此操作。

例如:

CREATE TABLE db.table(id UNIQUE, name);

INSERT OR REPLACE INTO db.table (id, name) VALUES (5, 'exep');

如果表中存在id为5,则此命令的行为类似于更新,否则它将是插入。

有关详细信息,请参阅http://www.sqlite.org/lang_conflict.html

相关问题