sqlite.js
4.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
class SQLite {
constructor(name, version, description, size) {
this.name = name
this.version = version || '1.0'
this.description = description || 'SQLite DB'
this.size = size || 50 * 1024 * 1024 // 50MB
this.db = null
}
init() {
return new Promise((resolve, reject) => {
plus.sqlite.openDatabase({
name: this.name, // 数据库名称
path: `_doc/${this.name}.db`, // 数据库地址
success: resolve, // 直接使用 resolve
fail: reject // 直接使用 reject
})
})
}
selectSql(sql) {
return new Promise((resolve, reject) => {
uni.$logger.local.info(`执行SQL语句: ${sql}`)
plus.sqlite.selectSql({
name: this.name,
sql,
success: result => {
// 处理查询结果,尝试还原数组或对象字符串
const processedRows = result.map(row =>
Object.fromEntries(
Object.entries(row).map(([key, value]) => {
try {
// 尝试将字符串解析为对象或数组
return [key, JSON.parse(value)]
} catch {
// 如果解析失败,保留原始值
return [key, value]
}
})
)
)
resolve(processedRows)
},
fail: reject
})
})
}
executeSql(sql) {
return new Promise((resolve, reject) => {
uni.$logger.local.info(`执行SQL语句: ${sql}`)
plus.sqlite.executeSql({
name: this.name,
sql,
success: resolve,
fail: reject
})
})
}
async isTableExists(tableName) {
const sql = `SELECT COUNT(*) as isTable FROM sqlite_master WHERE type='table' and name='${tableName}'`
try {
const result = await this.selectSql(sql)
return result[0].isTable ? true : false
} catch (error) {
console.error('检查表是否存在出错: ', error)
throw error
}
}
// 创建新表示例
createTable(tableName, columns) {
const sql = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(', ')})`
return this.executeSql(sql)
}
// 查询示例
select(tabName, where, order) {
let sql = `SELECT * FROM ${tabName}`
if (where) {
const dataKeys = Object.keys(where)
const conditions = dataKeys.map(key => `${key}=${JSON.stringify(where[key])}`).join(' AND ')
sql += ` WHERE ${conditions}`
}
if (order) {
const orderKey = Object.keys(order)[0] // 获取排序字段
const orderType = order[orderKey] // 获取排序类型
sql += ` ORDER BY ${orderKey} ${orderType}`
}
return this.selectSql(sql)
}
// 插入示例
insert(tabName, keyValues) {
const keys = Object.keys(keyValues)
const keyStr = keys.join(', ')
const valStr = keys
.map(key => {
const value = keyValues[key]
// 使用公共方法进行格式化
return `${this.formatValue(value)}`
})
.join(', ')
const sql = `INSERT INTO ${tabName} (${keyStr}) VALUES (${valStr})`
return this.executeSql(sql)
}
// 更新示例
update(tabName, setData, where) {
const dataKeys = Object.keys(setData)
const setStr = dataKeys
.map(key => {
const value = setData[key]
return `${key} = ${this.formatValue(value)}`
})
.join(', ')
const whereKeys = Object.keys(where)
const whereStr = whereKeys
.map(key => {
const value = where[key]
return `${key} = ${this.formatValue(value)}`
})
.join(' AND ')
const sql = `UPDATE ${tabName} SET ${setStr} WHERE ${whereStr}`
return this.executeSql(sql)
}
// 删除示例
delete(tabName, where) {
const whereKeys = Object.keys(where)
const whereStr = whereKeys
.map(key => {
const value = where[key]
return `${key} = ${this.formatValue(value)}`
})
.join(' AND ')
const sql = `DELETE FROM ${tabName} WHERE ${whereStr}`
return this.executeSql(sql)
}
isOpen() {
let isopen = plus.sqlite.isOpenDatabase({
name: this.name,
path: `_doc/${this.name}.db`
})
return isopen
}
close() {
if (this.db) {
this.db.close()
this.db = null
console.log('数据库连接已关闭')
}
}
drop(tabName) {
const sql = `DROP TABLE ${tabName}`
return this.executeSql(sql)
}
formatValue(value) {
return typeof value === 'object' && value !== null ? `'${JSON.stringify(value)}'` : `'${value}'`
}
}
export default SQLite
// 使用示例
/* const db = new SQLite('mydb', '1.0', 'Test DB', 1 * 1024 * 1024);
db.init().then(() => {
// 进行数据库操作
}).catch(error => {
console.error('数据库初始化失败: ', error);
});*/