例子
let db = new SQLiteUtil("/sdcard/A_My_DB/sqlite.db");db.fastCreateTable("user_table",{name: "",online: false,},["name"]
);
let row_id = db.insert("user_table", {name: "小明5",online: true,
});if (row_id == -1) {console.log("新增失败");
}
console.log("新数据的ID", row_id);
let r2 = db.update("user_table", { online: false }, "name=? and online = ?", ["小明5", 1]);
if (r2 == 0) {console.log("修改失败");
}
console.log("受影响的行数", r2);
find_all();db.deleteDbFile()function find_all() {let arr = db.find("select * from user_table");for (let i = 0; i < arr.length; i++) {let item = arr[i];console.log(item);}
}
代码
var SQLiteUtil = (function () {function SQLiteUtil(file_path) {importClass(android.database.sqlite.SQLiteDatabase);importClass(android.content.ContentValues);this._db_file_path = file_path;}SQLiteUtil.prototype.fastCreateTable = function (tableName, data, uniqueArr) {var columnArr = [];var itemName = "";for (var key in data) {switch (typeof data[key]) {case "number":itemName = key + " INTEGER DEFAULT 0";break;case "boolean":itemName = key + " INTEGER DEFAULT 0";break;default:itemName = key + " TEXT DEFAULT ''";break;}if (uniqueArr != undefined && uniqueArr.indexOf(key) > -1) {itemName += " unique";}columnArr.push(itemName);}this.createTable(tableName, columnArr);};SQLiteUtil.prototype.createTable = function (tableName, columns) {this._log("init", columns);try {files.ensureDir(this._db_file_path);this.execSQL("create table IF NOT EXISTS " + tableName + "(id integer primary key autoincrement," + columns.join(",") + ")");}catch (e) {this._error("createTable error: " + e);throw e;}};SQLiteUtil.prototype.find = function (sqlStr) {this._log("find");var res = [];var db;try {db = this._getDBConnection();res = this._getCursorDataArr(db.rawQuery(sqlStr, null));}catch (e) {this._error("find error: " + e);throw e;}finally {db && db.close();}return res;};SQLiteUtil.prototype.insert = function (tableName, jsonObj, nullColumnHack) {this._log("insert");nullColumnHack = nullColumnHack || undefined;var res = -1;var db;try {db = this._getDBConnection();db.beginTransaction();res = db.insert(tableName, nullColumnHack, this._getContentValues(jsonObj));db.setTransactionSuccessful(); }catch (e) {this._error("insert error: " + e);throw e;}finally {db && db.endTransaction();db && db.close();}return res;};SQLiteUtil.prototype.delete = function (tableName, whereClause, whereArgs) {this._log("delete");var res = 0;var db;try {db = this._getDBConnection();db.beginTransaction();res = db.delete(tableName, whereClause, whereArgs);db.setTransactionSuccessful(); }catch (e) {this._error("delete error: " + e);throw e;}finally {db && db.endTransaction();db && db.close();}return res;};SQLiteUtil.prototype.update = function (tableName, jsonObj, whereClause, whereArgs) {this._log("update");var res = 0;var db;try {db = this._getDBConnection();res = db.update(tableName, this._getContentValues(jsonObj), whereClause, whereArgs);}catch (e) {this._error("update error: " + e);throw e;}finally {db && db.close();}return res;};SQLiteUtil.prototype.replace = function (tableName, jsonObj, nullColumnHack) {nullColumnHack = nullColumnHack || undefined;var res = -1;var db;try {db = this._getDBConnection();res = db.replace(tableName, nullColumnHack, this._getContentValues(jsonObj));}catch (e) {this._error("replace error: " + e);throw e;}finally {db && db.close();}return res;};SQLiteUtil.prototype.dropTable = function (tableName) {try {this.execSQL("drop table if exists " + tableName);}catch (e) {this._error("dropTable error: " + e);throw e;}};SQLiteUtil.prototype.clearTable = function (tableName) {try {this.execSQL("delete from " + tableName);}catch (e) {this._error("clearTable error: " + e);throw e;}};SQLiteUtil.prototype.resetTableSequence = function (tableName) {try {this.execSQL("UPDATE sqlite_sequence SET seq = 0 WHERE name = '" + tableName + "'");}catch (e) {this._error("resetTableSequence error: " + e);throw e;}};SQLiteUtil.prototype.execSQL = function (sqlStr) {var db;try {db = this._getDBConnection();db.execSQL(sqlStr);}catch (e) {throw e;}finally {db && db.close();}};SQLiteUtil.prototype.needUpgrade = function (newVersion) {var res = false;var db;try {db = this._getDBConnection();res = db.needUpgrade(newVersion);}catch (e) {this._error("needUpgrade error:" + e);throw e;}finally {db && db.close();}return res;};SQLiteUtil.prototype.deleteDbFile = function () {if (files.exists(this._db_file_path)) {files.remove(this._db_file_path);this._log("数据库删除成功,地址:" + this._db_file_path);}};SQLiteUtil.prototype._getCursorDataArr = function (cursor) {var res = [];if (cursor) {try {cursor.moveToFirst();this._log("cursor count: " + cursor.getCount());var columnNameArr = cursor.getColumnNames();if (cursor.getCount() > 0) {do {var resItem = {};for (var nameIndex = 0; nameIndex < columnNameArr.length; nameIndex++) {var nameItem = columnNameArr[nameIndex];var columnIndex = cursor.getColumnIndex(nameItem);if (columnIndex > -1) {var itemValue = void 0;switch (cursor.getType(columnIndex)) {case 0: itemValue = null;break;case 1: itemValue = cursor.getInt(columnIndex);break;case 2: itemValue = cursor.getFloat(columnIndex);break;case 3: itemValue = cursor.getString(columnIndex);break;case 4: itemValue = cursor.getBlob(columnIndex);break;default:itemValue = cursor.getString(columnIndex);break;}resItem[nameItem] = itemValue;}}res.push(resItem);} while (cursor.moveToNext());}}catch (e) {this._error("_getCursorDataArr error: " + e);throw e;}finally {cursor.close();}}return res;};SQLiteUtil.prototype._getContentValues = function (jsonObj) {var cv = new ContentValues();if (jsonObj) {for (var key in jsonObj) {var item = jsonObj[key];switch (typeof item) {case "number":cv.put(key, java.lang.Integer(item));break;case "boolean":cv.put(key, java.lang.Boolean(item));break;case "boolean":cv.put(key, java.lang.Boolean(item));break;default:cv.put(key, java.lang.String(item));break;}}}return cv;};SQLiteUtil.prototype._log = function () {var data = [];for (var _i = 0; _i < arguments.length; _i++) {data[_i] = arguments[_i];}var msg = [];for (var i = 0; i < arguments.length; i++) {var item = arguments[i];msg.push(item);}console.log(msg.join(" "));};SQLiteUtil.prototype._error = function (msg) {console.error(msg);};SQLiteUtil.prototype._getDBConnection = function () {return SQLiteDatabase.openOrCreateDatabase(this._db_file_path, null);};return SQLiteUtil;
}());