Ionic Cordova SQLite,如果不存在则插入数据,如果数据存在则替换旧数据

时间:2016-09-29 08:11:21

标签: sql database sqlite

我正在使用Ionic和Cordova SQLite开发一个应用程序。如果sqlite中不存在数据,但是如果数据存在于sqlite中,则应用程序将数据插入到sqlite中。然后,应用程序正在替换旧数据。以下是我的代码。但是我无法将数据插入到sqlite数据库中。

创建数据库

db = window.openDatabase("chatChannel.db", "1", "Demo SQLite Test", "2000");
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS chat_channel(id interger primary key, channel_name text unique, last_text text)")

插入数据

  var query = "INSERT INTO chat_channel (channel_name, last_text) VALUES(?,?) ON DUPLICATE KEY UPDATE (last_text) VALUES (?)";
  $cordovaSQLite.execute(db, query, [channel, $scope.messageContent], [$scope.messageContent]);

如果sqlite数据库中不存在记录,我是否知道如何将数据插入cordova s​​qlite;如果数据库中存在数据则更新数据。

1 个答案:

答案 0 :(得分:0)

您可以使用REPLACE(https://www.sqlite.org/lang_insert.html

REPLACE INTO chat_channel (channel_name, last_text) VALUES(?,?)

但是要使其正常工作,您需要在请求中包含唯一或主键(在您的情况下,如果channel_name是chat_channel的主键,或者它是唯一的),请参阅{{3}有关REPLACE冲突解决的详细信息