先安装
js
yarn add react-native-sqlite-storage
sqlite-helper.js工具包的具体代码
js
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _regenerator=_interopRequireDefault(require("@babel/runtime/regenerator"));var _classCallCheck2=_interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));var _createClass2=_interopRequireDefault(require("@babel/runtime/helpers/createClass"));var _reactNativeSqliteStorage=_interopRequireDefault(require("react-native-sqlite-storage"));_reactNativeSqliteStorage.default.DEBUG(__DEV__);_reactNativeSqliteStorage.default.enablePromise(true);function isEmptyObj(obj){return Object.prototype.toString.call(obj)==='[object Object]'&&Object.keys(obj).length===0;}function isObject(target){return Object.prototype.toString.call(target)==='[object Object]';}var SQLite=function(){function SQLite(){(0,_classCallCheck2.default)(this,SQLite);for(var _len=arguments.length,rest=new Array(_len),_key=0;_key<_len;_key++){rest[_key]=arguments[_key];}if(rest.length===1&&isObject(rest[0])){var databaseOptions=rest[0];this.databaseOptions=databaseOptions;}else{var databaseName=rest[0],databaseVersion=rest[1],databaseDisplayName=rest[2],_rest$=rest[3],databaseSize=_rest$===void 0?-1:_rest$;this.databaseName=databaseName;this.databaseVersion=databaseVersion;this.databaseDisplayName=databaseDisplayName;this.databaseSize=databaseSize;}this.successInfo=function(text,absolutely){if(__DEV__){if(absolutely===true){console.log(text);}else{console.log("[SQLiteHelper] info: database "+text+" success.");}}};this.warningInfo=function(text,absolutely){if(__DEV__){if(absolutely===true){console.warn(text);}else{console.warn("[SQLiteHelper] warn: "+text+".");}}};this.errorInfo=function(text,err,absolutely){if(__DEV__){if(absolutely===true){console.error(text);}else{console.error("[SQLiteHelper] err: database "+text+" error, "+err.message);}}};this.open=this._open.bind(this);this.close=this._close.bind(this);this.createTable=this._createTable.bind(this);this.dropTable=this._dropTable.bind(this);this.insertItems=this._insertItems.bind(this);this.deleteItem=this._deleteItem.bind(this);this.updateItem=this._updateItem.bind(this);this.selectItems=this._selectItems.bind(this);}(0,_createClass2.default)(SQLite,[{key:"_open",value:function _open(){var _this=this;var _await$SQLiteStorage$,failed,openDatabase;return _regenerator.default.async(function _open$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=2;return _regenerator.default.awrap(_reactNativeSqliteStorage.default.echoTest().catch(function(err){return{failed:err};}));case 2:_await$SQLiteStorage$=_context.sent;failed=_await$SQLiteStorage$.failed;if(!failed){_context.next=6;break;}return _context.abrupt("return",{err:failed});case 6:if(this.databaseOptions){openDatabase=function openDatabase(){return _reactNativeSqliteStorage.default.openDatabase(_this.databaseOptions);};}else{openDatabase=function openDatabase(){return _reactNativeSqliteStorage.default.openDatabase(_this.databaseName,_this.databaseVersion,_this.databaseDisplayName,_this.databaseSize);};}return _context.abrupt("return",openDatabase().then(function(db){_this.successInfo('open');_this.db=db;return{res:db};}).catch(function(err){_this.errorInfo('open',err);return{err:err};}));case 8:case"end":return _context.stop();}},null,this,null,Promise);}},{key:"_close",value:function _close(){var _this2=this;return _regenerator.default.async(function _close$(_context2){while(1)switch(_context2.prev=_context2.next){case 0:if(!this.db){_context2.next=2;break;}return _context2.abrupt("return",this.db.close().then(function(res){_this2.successInfo('close');_this2.db=null;return{res:res||'Database CLOSED'};}).catch(function(err){_this2.errorInfo('close',err);return{err:err};}));case 2:this.warningInfo('Database was not OPENED');return _context2.abrupt("return",{res:'Database was not OPENED'});case 4:case"end":return _context2.stop();}},null,this,null,Promise);}},{key:"_createTable",value:function _createTable(tableInfo){var _this3=this;var tableName,tableFields,_await$this$open,err,sqlStr;return _regenerator.default.async(function _createTable$(_context3){while(1)switch(_context3.prev=_context3.next){case 0:_context3.prev=0;tableName=tableInfo.tableName,tableFields=tableInfo.tableFields;if(!(!tableName||!tableFields)){_context3.next=4;break;}throw new Error('Required parameter missing');case 4:if(this.db){_context3.next=11;break;}_context3.next=7;return _regenerator.default.awrap(this.open());case 7:_await$this$open=_context3.sent;err=_await$this$open.err;if(!err){_context3.next=11;break;}throw err;case 11:sqlStr=tableFields.reduce(function(sqlSegment,field,index,arr){return sqlSegment+" "+field.columnName+" "+field.dataType+" "+(index+1===arr.length?');':',');},"CREATE TABLE IF NOT EXISTS "+tableName+"(");_context3.next=14;return _regenerator.default.awrap(this.db.executeSql(sqlStr).then(function(res){_this3.successInfo('createTable');return{res:res};}).catch(function(err){_this3.errorInfo('createTable',err);return{err:err};}));case 14:return _context3.abrupt("return",_context3.sent);case 17:_context3.prev=17;_context3.t0=_context3["catch"](0);return _context3.abrupt("return",{err:_context3.t0});case 20:case"end":return _context3.stop();}},null,this,[[0,17]],Promise);}},{key:"_dropTable",value:function _dropTable(tableName){var _this4=this;var _await$this$open2,err;return _regenerator.default.async(function _dropTable$(_context4){while(1)switch(_context4.prev=_context4.next){case 0:_context4.prev=0;if(tableName){_context4.next=3;break;}throw new Error('Required parameter missing');case 3:if(this.db){_context4.next=10;break;}_context4.next=6;return _regenerator.default.awrap(this.open());case 6:_await$this$open2=_context4.sent;err=_await$this$open2.err;if(!err){_context4.next=10;break;}throw err;case 10:_context4.next=12;return _regenerator.default.awrap(this.db.executeSql("DROP TABLE "+tableName+";").then(function(res){_this4.successInfo('dropTable');return{res:res};}).catch(function(err){_this4.errorInfo('dropTable',err);return{err:err};}));case 12:return _context4.abrupt("return",_context4.sent);case 15:_context4.prev=15;_context4.t0=_context4["catch"](0);return _context4.abrupt("return",{err:_context4.t0});case 18:case"end":return _context4.stop();}},null,this,[[0,15]],Promise);}},{key:"_insertItems",value:function _insertItems(tableName,items){var _this5=this;var _await$this$open3,err,sqlStrArr;return _regenerator.default.async(function _insertItems$(_context5){while(1)switch(_context5.prev=_context5.next){case 0:_context5.prev=0;if(!(!tableName||!items)){_context5.next=3;break;}throw new Error('Required parameter missing');case 3:if(!(typeof tableName!=='string')){_context5.next=5;break;}throw new Error("Parameter tableName expects string but "+typeof tableName);case 5:if(Array.isArray(items)){_context5.next=7;break;}throw new Error("Parameter items expects array but "+typeof items);case 7:if(this.db){_context5.next=14;break;}_context5.next=10;return _regenerator.default.awrap(this.open());case 10:_await$this$open3=_context5.sent;err=_await$this$open3.err;if(!err){_context5.next=14;break;}throw err;case 14:sqlStrArr=items.map(function(item){var columns=Object.keys(item);var sqlStr=columns.reduce(function(sqlSegment,columnName,index,arr){return sqlSegment+" "+columnName+" "+(index+1===arr.length?')':',');},"INSERT INTO "+tableName+" (");sqlStr+=columns.reduce(function(sqlSegment,columnName,index,arr){return sqlSegment+" "+(typeof item[columnName]!=='number'?"'"+item[columnName]+"'":item[columnName])+" "+(index+1===arr.length?');':',');},' VALUES (');return sqlStr;});_context5.next=17;return _regenerator.default.awrap(this.db.sqlBatch(sqlStrArr).then(function(res){_this5.successInfo('insertItemsBatch');return{res:res||'All INSERT SQL done'};}).catch(function(err){_this5.errorInfo('insertItemsBatch',err);return{err:err};}));case 17:return _context5.abrupt("return",_context5.sent);case 20:_context5.prev=20;_context5.t0=_context5["catch"](0);return _context5.abrupt("return",{err:_context5.t0});case 23:case"end":return _context5.stop();}},null,this,[[0,20]],Promise);}},{key:"_deleteItem",value:function _deleteItem(tableName,conditions){var _this6=this;var _await$this$open4,err,sqlStr,_conditions$combine,combine,_conditions;return _regenerator.default.async(function _deleteItem$(_context6){while(1)switch(_context6.prev=_context6.next){case 0:_context6.prev=0;if(tableName){_context6.next=3;break;}throw new Error('Required parameter missing');case 3:if(this.db){_context6.next=10;break;}_context6.next=6;return _regenerator.default.awrap(this.open());case 6:_await$this$open4=_context6.sent;err=_await$this$open4.err;if(!err){_context6.next=10;break;}throw err;case 10:if(conditions){if(Array.isArray(conditions)&&conditions.length>0){sqlStr=conditions.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator=condition.operator,operator=_condition$operator===void 0?'=':_condition$operator,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?'AND':';');}return'';},"DELETE FROM "+tableName+" WHERE");}else if(isObject(conditions)&&!isEmptyObj(conditions)){_conditions$combine=conditions.combine,combine=_conditions$combine===void 0?'OR':_conditions$combine,_conditions=conditions.conditions;sqlStr=_conditions.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator2=condition.operator,operator=_condition$operator2===void 0?'=':_condition$operator2,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?combine:';');}return'';},"DELETE FROM "+tableName+" WHERE");}else if(typeof conditions==='string'){sqlStr="DELETE FROM "+tableName+" WHERE "+conditions+";";}}else{sqlStr="DELETE FROM "+tableName+";";}_context6.next=13;return _regenerator.default.awrap(this.db.executeSql(sqlStr).then(function(res){_this6.successInfo("SQLiteStorage deleteItem success: \u5F71\u54CD "+res[0].rowsAffected+" \u884C",true);return{res:res||'DELETE SQL done'};}).catch(function(err){_this6.errorInfo('deleteItem',err);return{err:err};}));case 13:return _context6.abrupt("return",_context6.sent);case 16:_context6.prev=16;_context6.t0=_context6["catch"](0);return _context6.abrupt("return",{err:_context6.t0});case 19:case"end":return _context6.stop();}},null,this,[[0,16]],Promise);}},{key:"_updateItem",value:function _updateItem(tableName,item,conditions){var _this7=this;var _await$this$open5,err,columns,sqlStr,_conditions$combine2,combine,_conditions;return _regenerator.default.async(function _updateItem$(_context7){while(1)switch(_context7.prev=_context7.next){case 0:_context7.prev=0;if(!(!tableName||!item)){_context7.next=3;break;}throw new Error('Required parameter missing');case 3:if(!(typeof tableName!=='string')){_context7.next=5;break;}throw new Error("Parameter tableName expects string but "+typeof tableName);case 5:if(isObject(item)){_context7.next=7;break;}throw new Error("Parameter item expects object but "+Object.prototype.toString.call(item));case 7:if(this.db){_context7.next=14;break;}_context7.next=10;return _regenerator.default.awrap(this.open());case 10:_await$this$open5=_context7.sent;err=_await$this$open5.err;if(!err){_context7.next=14;break;}throw err;case 14:columns=Object.keys(item);sqlStr=columns.reduce(function(sqlSegment,columnName,index,arr){return sqlSegment+" "+columnName+"="+(typeof item[columnName]!=='number'?"'"+item[columnName]+"'":item[columnName])+" "+(index+1!==arr.length?',':'');},"UPDATE "+tableName+" SET");if(conditions){if(Array.isArray(conditions)&&conditions.length>0){sqlStr+=conditions.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator3=condition.operator,operator=_condition$operator3===void 0?'=':_condition$operator3,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?'AND':';');}return'';},'WHERE');}else if(isObject(conditions)&&!isEmptyObj(conditions)){_conditions$combine2=conditions.combine,combine=_conditions$combine2===void 0?'OR':_conditions$combine2,_conditions=conditions.conditions;sqlStr+=_conditions.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator4=condition.operator,operator=_condition$operator4===void 0?'=':_condition$operator4,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?combine:';');}return'';},'WHERE');}else if(typeof conditions==='string'){sqlStr+="WHERE "+conditions+";";}}else sqlStr+=';';_context7.next=19;return _regenerator.default.awrap(this.db.executeSql(sqlStr).then(function(res){_this7.successInfo("SQLiteStorage updateItem success: \u5F71\u54CD "+res[0].rowsAffected+" \u884C",true);return{res:res||'UPDATE SQL done'};}).catch(function(err){_this7.errorInfo('updateItem',err);return{err:err};}));case 19:return _context7.abrupt("return",_context7.sent);case 22:_context7.prev=22;_context7.t0=_context7["catch"](0);return _context7.abrupt("return",{err:_context7.t0});case 25:case"end":return _context7.stop();}},null,this,[[0,22]],Promise);}},{key:"_selectItems",value:function _selectItems(tableName){var _this8=this;var config,_config$columns,columns,conditions,pageNo,pageLength,_await$this$open6,err,sqlStr,_conditions$combine3,combine,_conditions,_conditions$combine4,_combine,_conditions2,limit,offset,_args8=arguments;return _regenerator.default.async(function _selectItems$(_context8){while(1)switch(_context8.prev=_context8.next){case 0:config=_args8.length>1&&_args8[1]!==undefined?_args8[1]:{};_context8.prev=1;_config$columns=config.columns,columns=_config$columns===void 0?'*':_config$columns,conditions=config.conditions,pageNo=config.pageNo,pageLength=config.pageLength;if(tableName){_context8.next=5;break;}throw new Error('Required parameter missing');case 5:if(this.db){_context8.next=12;break;}_context8.next=8;return _regenerator.default.awrap(this.open());case 8:_await$this$open6=_context8.sent;err=_await$this$open6.err;if(!err){_context8.next=12;break;}throw err;case 12:if(columns==='*'){if(conditions){if(Array.isArray(conditions)&&conditions.length>0){sqlStr=conditions.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator5=condition.operator,operator=_condition$operator5===void 0?'=':_condition$operator5,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?'AND':'');}return'';},"SELECT * FROM "+tableName+" WHERE");}else if(isObject(conditions)&&!isEmptyObj(conditions)){_conditions$combine3=conditions.combine,combine=_conditions$combine3===void 0?'OR':_conditions$combine3,_conditions=conditions.conditions;sqlStr=_conditions.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator6=condition.operator,operator=_condition$operator6===void 0?'=':_condition$operator6,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?combine:'');}return'';},"SELECT * FROM "+tableName+" WHERE");}else if(typeof conditions==='string'){sqlStr="SELECT * FROM "+tableName+" WHERE "+conditions+";";}}else{sqlStr="SELECT * FROM "+tableName;}}else{sqlStr=columns.reduce(function(sqlSegment,column,index,arr){return sqlSegment+" "+column+" "+(index+1!==arr.length?',':'');},'SELECT');if(conditions){if(Array.isArray(conditions)&&conditions.length>0){sqlStr+=conditions.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator7=condition.operator,operator=_condition$operator7===void 0?'=':_condition$operator7,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?'AND':'');}return'';},"FROM "+tableName+" WHERE");}else if(isObject(conditions)&&!isEmptyObj(conditions)){_conditions$combine4=conditions.combine,_combine=_conditions$combine4===void 0?'OR':_conditions$combine4,_conditions2=conditions.conditions;sqlStr+=_conditions2.reduce(function(sqlSegment,condition,index,arr){var columnName=condition.columnName,_condition$operator8=condition.operator,operator=_condition$operator8===void 0?'=':_condition$operator8,value=condition.value;if(columnName&&value){var _value=typeof value!=='number'?"'"+value+"'":value;return sqlSegment+" "+columnName+operator+_value+" "+(index+1!==arr.length?_combine:'');}return'';},"FROM "+tableName+" WHERE");}else if(typeof conditions==='string'){sqlStr+="FROM "+tableName+" WHERE "+conditions;}}else{sqlStr+="FROM "+tableName;}}if(pageNo&&pageLength){limit=pageNo*pageLength;offset=pageLength*(pageNo-1)>0?pageLength*(pageNo-1):0;sqlStr+=" limit "+limit+" offset "+offset+";";}else{sqlStr+=';';}_context8.next=16;return _regenerator.default.awrap(this.db.executeSql(sqlStr).then(function(res){if(res&&res[0]&&res[0].rows){_this8.successInfo("SQLiteStorage selectItems success: \u67E5\u8BE2\u5230 "+res[0].rows.length+" \u884C",true);var queryResult=[];var len=res[0].rows.length;for(var i=0;i<len;i++){queryResult.push(res[0].rows.item(i));}return{res:queryResult};}return{res:res};}).catch(function(err){_this8.errorInfo('selectItems',err);return{err:err};}));case 16:return _context8.abrupt("return",_context8.sent);case 19:_context8.prev=19;_context8.t0=_context8["catch"](1);return _context8.abrupt("return",{err:_context8.t0});case 22:case"end":return _context8.stop();}},null,this,[[1,19]],Promise);}}],[{key:"delete",value:function _delete(databaseName){return _regenerator.default.async(function _delete$(_context9){while(1)switch(_context9.prev=_context9.next){case 0:return _context9.abrupt("return",_reactNativeSqliteStorage.default.deleteDatabase(databaseName).then(function(res){return{res:res||"Database "+databaseName+" DELETED"};}).catch(function(err){return{err:err};}));case 1:case"end":return _context9.stop();}},null,null,null,Promise);}}]);return SQLite;}();exports.default=SQLite;
接下来是我使用这个工具包封装的一些方法,存在(SQLHelper.js)文件中
这里的 name 属性指定了数据库的名称,createFromLocation 属性指定了从特定位置创建数据库,而 readOnly 属性指定了数据库是否为只读模式。
name 属性:你在这里提供的是数据库的名称 'taketeam_db'。这将是你创建或连接的数据库的名称。
createFromLocation 属性:这个属性设置为 1,表示数据库将从特定的位置创建。这通常意味着数据库已经在设备的特定位置存在,你只需连接到它而不是创建一个新的数据库。这个属性通常在移动应用程序中用于将预加载的数据库复制到设备上,以便应用程序可以使用。
readOnly 属性:这个属性设置为 false,表示数据库是可读写的。如果你将其设置为 true,则数据库将只能以只读模式打开,不能执行写操作。
createFromLocation 属性是用于从特定位置创建数据库的选项,通常在移动应用中使用。它的工作方式是根据应用程序的平台和配置来决定数据库的位置。具体来说:Android 平台:在 Android 上,这个属性通常用于从应用的资产文件夹中复制数据库文件到设备上。你可以将数据库文件放在 android/app/src/main/assets 目录中,然后设置 createFromLocation 属性为 1,这将告诉应用从资产文件夹中复制数据库文件到设备上。
iOS 平台:在 iOS 上,这个属性通常用于从应用的资源束中复制数据库文件。你可以将数据库文件放在应用的资源束中,并设置 createFromLocation 属性为 1,应用会尝试从资源束中复制数据库文件到设备上。
其他平台:在其他平台上,具体的工作方式可能会有所不同,通常需要根据平台的特定要求进行配置。
总之,createFromLocation 属性是用于告诉应用从特定位置复制数据库文件到设备上的选项,具体的位置和工作方式取决于应用的平台和配置。你需要根据你的应用和数据库文件的存放位置来正确配置这个选项。如果你的数据库文件已经位于应用的资源或资产文件夹中,设置 createFromLocation 为 1 应该能够让应用正确地复制数据库文件到设备上。
我的数据库存放地址为:
js
E:\Taketeam_Frontend\android\app\src\main\assets\www\taketeam_db
js
import { async } from '@babel/runtime/helpers/regeneratorRuntime'
import SQLiteHelper from '../db/sqlite-helper'
// SQLiteHelper 执行实例方法之前不用手动打开open(自动检测并打开),而直接使用SQLite实例执行sql,需要手动打开
const dbTool = new SQLiteHelper({
name: 'taketeam_db',
createFromLocation: 1,
readOnly: false,
})
async function openDB (callBack) {
// 开启数据库
const { res, err } = await dbTool.open()
if (res) {
callBack(true)
} else {
console.log('数据库打开失败', err)
}
}
/**
* tableName 表名
* condition 条件
* callBack 回调函数
*/
async function search (tableName, condition, callBack) {
let config = { columns: '*' }
if (condition !== null) {
config = {
columns: '*',
conditions: [condition],
}
}
const { res, err } = await dbTool.selectItems(tableName, config)
if (res) {
callBack(res)
} else {
console.log('err', err)
}
}
/**
* tableName 表名
* condition 条件
* callBack 回调函数
*/
async function searchSingle (tableName, config, callBack) {
const { res, err } = await dbTool.selectItems(tableName, config)
if (res) {
callBack(res)
} else {
console.log('err', err)
}
}
/** 删除单项
* tableName 表名
* item_id 项目id
* callBack 回调函数
*/
async function remove (tableName, item_id, columnName, callBack) {
const condition = { columnName: columnName, value: item_id }
const { res, err } = await dbTool.deleteItem(tableName, [condition])
if (res) {
callBack(res)
} else {
console.log('err', err)
}
}
/** 批量删除
* tableName 表名
* item_ids 项目id
* callBack 回调函数
*/
async function multilRemove (tableName, item_ids, callBack) {
let conditionArr = []
item_ids.forEach(item => {
const content = { columnName: 'id', value: item }
conditionArr.push(content)
})
const command = { combine: 'OR', conditions: conditionArr }
const { res, err } = await dbTool.deleteItem(tableName, command)
if (res) {
callBack(res)
} else {
console.log('err', err)
}
}
/** 新增数据
* tableName 表名
* objects 对象数组
* callBack 回调函数
*/
async function insert (tableName, objects, callBack) {
const { res, err } = await dbTool.insertItems(tableName, objects)
if (res) {
callBack(res)
} else {
console.log('err', err)
}
}
/** 修改数据
* tableName 表名
* item_id 项目id
* objects 对象数组
* callBack 回调函数
*/
async function modify (tableName, columnName, objects, item_ids, callBack) {
let conditions = []
item_ids.forEach(item_id => {
const condition = { columnName: columnName, value: item_id }
conditions.push(condition)
})
const command = { combine: 'OR', conditions: conditions }
const { res, err } = await dbTool.updateItem(tableName, objects, command)
if (res) {
callBack(res)
} else {
console.log('err', err)
}
}
// 删除表数据(不删除结构)
function clear (tableName) {
// 清空表数据
dbTool.deleteItem(tableName, null) // 第二个参数传入null表示删除条件为空
.then(result => {
if (result.err) {
console.error('清空表' + tableName + '数据失败', result.err)
} else {
console.log('表数据已成功清空')
}
})
}
/**
* 清空表数据
*/
async function clearTable () {
// grade 班组表名
// train 训练记录表名
// sensor 设备表名
// user 学员表名
clear('user')
clear('grade')
clear('train')
clear('sensor')
}
export default {
openDB,
search,
searchSingle,
remove,
multilRemove,
insert,
clearTable,
modify,
}
可以根据项目需要在进行一次封装
js
import SQLHelper from './SQLHelper'
import Marco from '../utils/Marco'
// 获取班级列表
export function getGradeList (callBack) {
SQLHelper.search(Marco.GradeTb, null, res => {
callBack(res)
})
}
// 获取学生列表
export function getStuList (grade_id, callBack) {
const condition = { columnName: 'grade_id', value: grade_id }
SQLHelper.search(Marco.UserTb, condition, res => {
callBack(res)
})
}
// 创建一个班级
export function createClass (info, callBack) {
SQLHelper.insert(Marco.GradeTb, [info], () => {
callBack()
})
}
// 创建一个学员
export function createUser (info, callBack) {
SQLHelper.insert(Marco.UserTb, [info], () => {
callBack()
})
}
// 更新成员信息
export function updateUser (info, user_id, callBack) {
SQLHelper.modify(Marco.UserTb, 'id', info, [user_id], () => {
callBack()
})
}
// 更新班级学员数量
export function updateCounts (info, grade_id, callBack) {
SQLHelper.modify(Marco.GradeTb, 'id', info, [grade_id], () => {
callBack()
})
}
// 删除学员
export function delMember (item_ids, callBack) {
SQLHelper.multilRemove(Marco.UserTb, item_ids, () => {
callBack()
})
}
// 获取设备列表
export function getSensorList (callBack) {
SQLHelper.search(Marco.SensorTb, null, res => {
callBack(res)
})
}
// 更新臂带绑定关系
export function updateUserSensor (info, user_id, callBack) {
SQLHelper.modify(Marco.UserTb, 'id', info, [user_id], () => {
callBack()
})
}
// 查询新建班级的id
export function getClassId (info, callBack) {
const config = { columns: ['id'], conditions: [info] }
SQLHelper.searchSingle(Marco.GradeTb, config, res => {
callBack(res)
})
}
// 查询班级训练记录
export function getRecord (grade_id, callBack) {
const condition = { columnName: 'grade_id', value: grade_id }
SQLHelper.search(Marco.TrainTb, condition, res => {
callBack(res)
})
}
// 存储首次上课记录
export function saveSession (info, callBack) {
SQLHelper.insert(Marco.TrainTb, [info], res => {
callBack(res)
})
}
export function updateLastSession (info, grade_id, callBack) {
SQLHelper.modify(Marco.GradeTb, 'id', info, [grade_id], () => {
callBack()
})
}
// 查询新建班级的id
export function getSessionId (info, callBack) {
const config = { columns: ['id'], conditions: [info] }
SQLHelper.searchSingle(Marco.TrainTb, config, res => {
callBack(res)
})
}
// 每分钟存一次上课记录
export function updateSession (info, session_id, callBack) {
SQLHelper.modify(Marco.TrainTb, 'id', info, [session_id], () => {
callBack()
})
}
//修改班级名称
export function updateClassName (info, grade_id, callBack) {
SQLHelper.modify(Marco.GradeTb, 'id', info, [grade_id], () => {
callBack()
})
}
// 删除班级
export function delGrade (item_ids, callBack) {
SQLHelper.multilRemove(Marco.GradeTb, item_ids, () => {
callBack()
})
}
// 删除班级对应的学员
export function delGradeUsers (item_ids, callBack) {
SQLHelper.remove(Marco.UserTb, item_ids, 'grade_id', () => {
callBack()
})
}
// 删除成员正在绑定的心率设备
export function delUserbindSensor (info, sn, callBack) {
SQLHelper.modify(Marco.UserTb, 'sn', info, [sn], () => {
callBack()
})
}
// 批量添加成员
export function addMembers (info, callBack) {
SQLHelper.insert(Marco.UserTb, info, () => {
callBack()
})
}
// 根据臂带号查询用户信息
export function searchUserSensorNo (item_id, callBack) {
const condition = { columnName: 'sn', value: item_id }
SQLHelper.search(Marco.UserTb, condition, res => {
callBack(res)
})
}
// 批量更新用户信息
export function updateUserSensorInfo (item_ids, info, callBack) {
SQLHelper.modify(Marco.UserTb, 'id', info, item_ids, res => {
callBack(res)
})
}
// 删除没有数据的训练记录
export function delNodataRecord (item_ids, callBack) {
SQLHelper.remove(Marco.TrainTb, item_ids, 'id', () => {
callBack()
})
}
export function delTrainRecord (item_ids, callBack) {
SQLHelper.remove(Marco.TrainTb, item_ids, 'grade_id', () => {
callBack()
})
}