使用INSERT OR IGNORE INTO语句
//插入数据,有则忽略,无则创建
data.forEach(function (item,index) { var sql = "INSERT OR IGNORE INTO article(id, title, content, modify_time) VALUES (?, ?, ?, ?);"; app.db.execute(db, sql, [item.id, item.title, item.content, item.modifyTime]); });
//插入数据,有则替换,无则替换更新
data.forEach(function (item,index) { var sql = "INSERT OR REPLACE INTO article(id, title, content, modify_time) VALUES (?, ?, ?, ?);"; app.db.execute(db, sql, [item.id, item.title, item.content, item.modifyTime]); });
相关js
(function($) { // web sql $.db = {}; /** * 创建数据库 * @param {Object} name 数据库名称 * @param {Object} size 数据库大小 * @param {Object} version 数据库版本号 * @param {Object} display 数据库显示名称 */ $.db.create = function(name, size, version, describe){ var db_name = name ? name : 'test'; var db_size = size ? size : 10; var version = version ? version : '1.0'; var describe = describe ? describe : 'test'; return window.openDatabase(db_name, version, describe, db_size * 1024 * 1024); }; /** * 创建表 * @param {Object} db 数据库对象 */ $.db.createTable = function(db) { $.db.execute(db, "CREATE TABLE IF NOT EXISTS article(id INTEGER NOT NULL, title TEXT NOT NULL, content TEXT, modify_time DATETIME, UNIQUE (id))"); }; /** * 执行sql * @param {Object} db 数据库对象 * @param {Object} sql sql语句 * @param {Object} arg 参数 * @param {Object} callback 成功的回调函数 */ $.db.execute = function(db, sql, arg, callback){ if (!db && !sql) {return;} if (!arg) {arg = [];} if (!callback) {callback = null} var onError = function(tx, err){ console.log("Error:"+err.message) }; var onSuccess = function(context, results){ console.log("SQL执行成功"); if (callback) { callback(context, results) } }; db.transaction(function (context) { context.executeSql(sql, arg, onSuccess, onError); console.log("executeSql: "+sql) }); }; }(window.app = {}));