【问题标题】:Ionic Cordova SQLite, insert data if not exists, if data exists replace the old dataIonic Cordova SQLite,如果不存在则插入数据,如果存在则替换旧数据
【发布时间】:2016-09-29 22:33:15
【问题描述】:

我正在使用 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,如果数据库中存在数据,我可以更新数据。

【问题讨论】:

    标签: sql database sqlite


    【解决方案1】:

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

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

    但是,要使其正常工作,您需要在请求中包含唯一键或主键(在您的情况下,如果 channel_name 是 chat_channel 的主键,或者如果它是唯一的),请参阅https://www.sqlite.org/lang_conflict.html REPLACE的冲突解决细节

    【讨论】:

    • 它不起作用。我想要做的是当sqlite数据库中的channel_name可用时,它将替换数据库中的last_text,但如果channel_name不在数据库中,它将向数据库中插入一个新数据。
    猜你喜欢
    • 2017-04-24
    • 2015-03-31
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2020-06-22
    • 2011-01-13
    • 1970-01-01
    相关资源
    最近更新 更多