uni-app使用Sqlite

2022/6/25 2:20:53

本文主要是介绍uni-app使用Sqlite,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 

 

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);
					});
				});
			}
			
		}
	}

  



这篇关于uni-app使用Sqlite的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程