step2:封装常用操作(未对事务进行封装 HTML5+ API Reference (html5plus.org))
// //打开数据库 function openDb(name,path) { return new Promise((resolve,reject)=>{ plus.sqlite.openDatabase({ name: name, //这里是数据库的名称 path: path, //_doc是相对路径的应用私有文档目录 success: function(e){ console.log('数据库打开成功') resolve(e) }, fail: function(e){ console.log('数据库打开失败:' + JSON.stringify(e)) reject(e) } }) }) } function isOpened(name,path) { return plus.sqlite.isOpenDatabase({name:name,path:path}) } function closeDb(name) { return new Promise((resolve,reject)=>{ plus.sqlite.closeDatabase()({ name: name, //这里是数据库的名称 success: function(e){ console.log('数据库打开成功') resolve(e) }, fail: function(e){ console.log('数据库打开失败') reject(e) } }) }) } function selectSql(name,sqlText) { return new Promise((resolve,reject)=>{ plus.sqlite.selectSql({ name: name, //这里是数据库的名称 sql: sqlText, success: function(e){ console.log('selectSql查询成功:' + sqlText) resolve(e) }, fail: function(e){ console.log('selectSql查询失败:' + sqlText + "-异常信息:" + JSON.stringify(e)) reject(e) } }) }) } function executeSql(name,sqlText) { return new Promise((resolve,reject)=>{ plus.sqlite.executeSql({ name: name, //这里是数据库的名称 sql: sqlText, success: function(e){ console.log('数据库打开成功') resolve(e) }, fail: function(e){ console.log('executeSql执行失败:' + sqlText + '-异常信息:' + JSON.stringify(e)) reject(e) } }) }) } export { openDb, isOpened, closeDb, selectSql, executeSql }
使用举例:
(1)导入函数
import { isOpened,openDb, closeDb, selectSql,executeSql } from '@/utils/sqliteUtil';
(2)使用举例(注意这个路径-H5+路径规范和app路径相关只是)
onLoad() { const createTableSql = 'CREATE TABLE Test (TestID INT (100) PRIMARY KEY, TestName VARCHAR (200) )' const name = 'stock'; const path = '_doc/MyStock.db'; openDb(name, path).then(() => { const sql = 'select TestID,TestName from Test' executeSql(name, createTableSql).then(result => { console.log('executeSql',result) }) }) }, methods: { sqlTest() { const name = 'stock'; const path = '_doc/MyStock.db'; if(isOpened(name,path)){ const insertSql = 'INSERT INTO Test (TestID,TestName) VALUES (2, \'张三\');' executeSql(name,insertSql).then(result=>{ const sql = 'select TestID,TestName from Test'; selectSql(name, sql).then(result => { console.log(result); }) }) } else { openDb(name, path).then(() => { const sql = 'select TestID,TestName from Test'; selectSql(name, sql).then(result => { console.log(result); }); }); } } }