uniapp sqlite
时间: 2023-10-23 17:13:59 浏览: 166
对于uniapp中的sqlite数据库操作,可以使用uni-app提供的插件:uni-sqlite,需要先通过npm安装该插件。
安装命令:npm install --save uni-sqlite
使用示例:
``` js
import sqlite from '@/js_sdk/uni-sqlite/index.js'
let db = null;
export function openDB() {
return new Promise((resolve, reject) => {
db = uni.requireNativePlugin('sqlite').openDatabase({
name: 'test.db',
path: '_doc/test.db'
}, (res) => {
console.log('openDB success', res)
resolve(res)
}, (err) => {
console.log('openDB fail', err)
reject(err)
});
})
}
// 创建表
export function createTable() {
return new Promise((resolve, reject) => {
db.executeSql({
sql: 'CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INT NOT NULL)'
}, (res) => {
console.log('createTable success', res)
resolve(res)
}, (err) => {
console.log('createTable fail', err)
reject(err)
})
})
}
// 插入数据
export function insertData(data) {
return new Promise((resolve, reject) => {
db.executeSql({
sql: `INSERT INTO user (name, age) VALUES (?, ?)`,
args: [data.name, data.age]
}, (res) => {
console.log('insertData success', res)
resolve(res)
}, (err) => {
console.log('insertData fail', err)
reject(err)
})
})
}
// 查询数据
export function selectData() {
return new Promise((resolve, reject) => {
db.executeSql({
sql: `SELECT * FROM user`
}, (res) => {
console.log('selectData success', res)
resolve(res)
}, (err) => {
console.log('selectData fail', err)
reject(err)
})
})
}
// 删除数据
export function deleteData(id) {
return new Promise((resolve, reject) => {
db.executeSql({
sql: `DELETE FROM user WHERE id = ?`,
args: [id]
}, (res) => {
console.log('deleteData success', res)
resolve(res)
}, (err) => {
console.log('deleteData fail', err)
reject(err)
})
})
}
// 关闭数据库
export function closeDB() {
return new Promise((resolve, reject) => {
db.closeDatabase((res) => {
console.log('closeDB success', res)
resolve(res)
}, (err) => {
console.log('closeDB fail', err)
reject(err)
})
})
}
```
阅读全文