【问题标题】:SQLite updating rowSQLite 更新行
【发布时间】:2018-11-09 03:50:34
【问题描述】:

我正在使用 SQLite 数据库在 cordova 上开发一个移动应用程序。

应用程序通过 JSONP 从外部源接收数据并将数据写入数据库。

我需要使用sql查询来确定表中是否有一个具有特定id的条目,如果有则重写该行,如果没有则添加一个新的。

目前,数据写入函数如下所示:

    addNews: function (id, title, date, content) {
    databaseHandler.db.transaction(
        function (tx) {
            tx.executeSql(
                "insert into news(id, title, date, content) values(?, ?, ?, ?)",
                [id, title, date, content],
                function (tx, results) { },
                function (tx, error) {
                    console.log("add news error: " + error.message);
                }
            );
        },
        function (error) {
        },
        function () {
        }
    );
}

var url = "http://cp35240-wordpress.tw1.ru/wp-content/plugins/plugin/news.js";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);

function news(data) {
    var id = data.id;
    var title = data.title;
    var date = data.date;
    var content = data.content;  
    newsHandler.addNews(id, title, date, content);   
}

【问题讨论】:

  • 请描述您遇到的问题/没有按您预期的方式工作/正在发生什么错误/等等。
  • @landru27 目前表中的数据没有更新,而是重复了。 ibb.co/c7ghTV

标签: sql sqlite


【解决方案1】:

你可以使用INSERT OR REPLACE

语法

INSERT OR REPLACE INTO TABLE (column_list) 
VALUES (value_list);

所以在这里你可以使用

INSERT OR REPLACE INTO news(id, title, date, content) values(?, ?, ?, ?)

或者你可以使用UPSERT

INSERT INTO news(id, title, date, content) 
values(?, ?, ?, ?)
ON CONFLICT(Id) DO UPDATE 
    SET tile=?

进一步Read

【讨论】:

  • 这是行不通的。行继续重复...ibb.co/c7ghTV
  • @JS588787 请现在用 upsert 方式检查我已经更新了答案
  • 我收到一个错误:语句字符串中的“?”数与参数计数不匹配
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多