HTML5 曾提出 Web SQL Database 規格,讓前端可以直接在瀏覽器內以 SQL 語法操作 SQLite。以下示範如何在此基礎上封裝一個好不好用的工具物件,把建表、增修查刪都包成簡潔的方法。
先說清楚前提:Web SQL Database 規格已被 W3C 於 2010 年停止維護,Chrome、Safari 基於相容性仍保有實作,但 Firefox 與 Edge 從未支援。因此本文內容僅適合維護既有專案或理解歷史脈絡;新專案請改用 IndexedDB,或直接在瀏覽器端使用 sql.js(WebAssembly 編譯的 SQLite)。
var lanxDB = function (dbname) {
var db = openDatabase(dbname, '1.0.0', '', 65536);
return {
// 回傳資料庫名稱
getDBName: function () {
return dbname;
},
// 初始化:切換表格,必要時建表
init: function (tableName, colums) {
this.switchTable(tableName);
colums.length > 0 ? this.createTable(colums) : '';
return this;
},
// 建表,colums 為 [{name: 欄位名, type: 型別}]
createTable: function (colums) {
var sql = "CREATE TABLE IF NOT EXISTS " + this._table;
var t;
if (colums instanceof Array && colums.length > 0) {
t = [];
for (var i in colums) {
t.push(colums[i].name + ' ' + colums[i].type);
}
t = t.join(', ');
} else if (typeof colums == "object") {
t = colums.name + ' ' + colums.type;
}
sql = sql + " (" + t + ")";
var that = this;
db.transaction(function (tx) {
tx.executeSql(sql);
});
},
// 切換表格
switchTable: function (tableName) {
this._table = tableName;
return this;
},
// 插入資料並回呼,支援批次
// data 為陣列,每個元素是 {欄位名: 值}
insertData: function (data, callback) {
var that = this;
var sql = "INSERT INTO " + this._table;
if (data instanceof Array && data.length > 0) {
var cols = [], qs = [];
for (var i in data[0]) {
cols.push(i);
qs.push('?');
}
sql += " (" + cols.join(',') + ") Values (" + qs.join(',') + ")";
} else {
return false;
}
var p = [], d = data, r = [];
for (var i = 0, dLength = d.length; i < dLength; i++) {
var k = [];
for (var j in d[i]) {
k.push(d[i][j]);
}
p.push(k);
}
var queue = function (b, result) {
if (result) {
r.push(result.insertId || result.rowsAffected);
}
if (p.length > 0) {
db.transaction(function (tx) {
tx.executeSql(sql, p.shift(), queue, that.onfail);
});
} else {
if (callback) {
callback.call(this, r);
}
}
};
queue();
},
_where: '',
// where 條件,支援物件或字串
where: function (where) {
if (typeof where === 'object') {
var j = this.toArray(where);
this._where = j.join(' and ');
} else if (typeof where === 'string') {
this._where = where;
}
return this;
},
// 更新資料
updateData: function (data, callback) {
var that = this;
var sql = "Update " + this._table;
data = this.toArray(data).join(',');
sql += " Set " + data + " where " + this._where;
this.doQuery(sql, callback);
},
// 存在則更新,不存在則插入
saveData: function (data, callback) {
var sql = "Select * from " + this._table + " where " + this._where;
var that = this;
this.doQuery(sql, function (r) {
if (r.length > 0) {
that.updateData(data, callback);
} else {
that.insertData([data], callback);
}
});
},
// 查詢
getData: function (callback) {
var that = this;
var sql = "Select * from " + that._table;
that._where.length > 0 ? sql += " where " + that._where : "";
that.doQuery(sql, callback);
},
// 內部查詢方法
doQuery: function (sql, callback) {
var that = this;
var a = [];
var bb = function (b, result) {
if (result.rows.length) {
for (var i = 0; i < result.rows.length; i++) {
a.push(result.rows.item(i));
}
} else {
a.push(result.rowsAffected);
}
if (callback) {
callback.call(that, a);
}
};
db.transaction(function (tx) {
tx.executeSql(sql, [], bb, that.onfail);
});
},
// 刪除
deleteData: function (callback) {
var that = this;
var sql = "delete from " + that._table;
that._where.length > 0 ? sql += " where " + that._where : '';
that.doQuery(sql, callback);
},
// 刪表
dropTable: function () {
var sql = "DROP TABLE IF EXISTS " + this._table;
this.doQuery(sql);
},
_error: '',
onfail: function (t, e) {
this._error = e.message;
console.log('----sqlite:' + e.message);
},
// 把物件轉成 "key='value'" 形式的陣列
toArray: function (obj) {
var t = [];
obj = obj || {};
if (obj) {
for (var i in obj) {
t.push(i + "='" + obj[i] + "'");
}
}
return t;
}
};
};
/* 使用範例
var db = new lanxDB('testDB');
db.init('channel_list', [
{ name: 'id', type: 'integer primary key autoincrement' },
{ name: 'name', type: 'text' },
{ name: 'link', type: 'text' },
{ name: 'cover', type: 'text' },
{ name: 'updatetime',type: 'integer' },
{ name: 'orders', type: 'integer' }
]);
db.switchTable('channel_list').insertData([
{ name: 'aa', link: 'ss', updatetime: new Date().getTime() },
{ name: 'bb', link: 'kk', updatetime: new Date().getTime() }
]);
db.where({ name: 'aa' }).getData(function (result) {
console.log(result); // 陣列
});
db.where({ name: 'aa' }).deleteData(function (result) {
console.log(result[0]); // 刪除筆數
});
db.where({ name: 'bb' }).saveData({ link: 'jj' }, function (result) {
console.log(result); // 影響筆數
});
*/
鏈式呼叫:init、switchTable、where 都回傳 this,讓程式碼可以寫成 db.where({...}).deleteData(cb),讀起來接近口語。
批次佇列:insertData 用一個 queue 函式反覆 shift 參數陣列,確保每筆 executeSql 依序完成後才收集回呼結果,避免併發造成的錯誤。
物件轉 where:toArray 把 {name:'aa'} 轉為 name='aa',省下大量手寫條件字串的功夫。
這個封裝把值直接內插進 SQL 字串(toArray 與 updateData),存在 SQL Injection 風險。若要在任何真實環境使用,必須全部改為參數化查詢,把值放在 executeSql 的第二個參數中,而不是拼進語法裡。
此外,openDatabase 的 65536 是資料庫上限位元組數,正式環境應依需求調整並處理超出配額的例外。
若需要的是「關聯式查詢能力」,sql.js 或 wa-sqlite 把 SQLite 完整編譯成 WebAssembly,效能與相容性都遠優於 Web SQL,資料還可透過 Origin Private File System 持久化。若只是需要鍵值或結構化儲存,IndexedDB 才是標準答案,搭配 idb、Dexie 這類包裝套件能大幅降低使用門檻。