elctron 使用node模块记录之sqlite3
一些小型项目用不上mysql ,electron即可一体化实现,当然需要本地数据库的增删改查,sqlite就是最好的选择,封装增删改查的代码:
var sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('recognition')
function mydb() { };
function genID(length) { //生成id
return Number(Math.random().toString().substr(3, length) + new Date().getTime()).toString(36);
}
// 获取长度
function nowTime() {
return new Date().getTime()
}
// 增:
// var addUser = db.prepare("INSERT OR REPLACE INTO User VALUES (?,?,?,?,?,?,?)");
// // var addLog = db.prepare("INSERT OR REPLACE INTO User (Id,UserName,RealName,Phone,Remarks,PassWord,CreateDate) VALUES (?,?,?,?,?,?,?)");
// addUser.run(genID, '123', "123", '123', "123", '123', "123");
// add.run("小白2",3);
// add.run("小白3",3);
// add.finalize();
// 删:
// var del=db.prepare("DELETE from human where name =?");
// del.run('小白1');
// del.finalize();
//改:
// var r = db.prepare("UPDATE human set name =? where id =2");
// r.run("小白22222");
// r.finalize();
// 查 指定字段
// db.each("SELECT id, name,age FROM human", function(err, row) {
// console.log(`${row.id} 姓名:${row.name} 年龄:${row.age}`);
// });
// 查 所有字段
// 查 按条件
//select count(Id) from User
// db.each("SELECT id, name,age FROM human where name=?",'小白2', function(err, row) {
// console.log(`${row.id} 姓名:${row.name} 年龄:${row.age}`);
// });
mydb.prototype.get = (key, parmse, callback, qurey) => {
var res = {}
var sql = ''
var where = ''
if (qurey) {
Object.keys(qurey).forEach((key, idx) => {
// 这里 obj[key] 便是对象的每一个的值
if (qurey[key]) {
if (idx == 0) {
if (key == 'time') {
where = `where date>${qurey.time[0]} and date<${qurey.time[1]}`
} else {
where = `where ${key}=${qurey[key]}`
}
} else {
if (key == 'time') {
where += ' ' + `and date>${qurey.time[0]} and date<${qurey.time[1]}`
} else {
where += ' ' + `and ${key}=${qurey[key]}`
}
}
}
})
// if (qurey.time && qurey.type) {
// where = `where date>${qurey.time[0]} and date<${qurey.time[1]} and type=${qurey.type}`
// } else if (qurey.time) {
// where = `where date>${qurey.time[0]} and date<${qurey.time[1]}`
// } else if (qurey.type == '智能检测' || qurey.type == '专家模式') {
// where = `where type=${qurey.type}`
// } else if (qurey.res == '正常' || qurey.res == '异常') {
// where = `where res=${qurey.res}`
// }
}
//判断是否需要分页
if (key == 'history') {
if (!parmse.page) {
sql = `select * from ${key} ${where} order by date desc`
} else {
sql = `select * from ${key} ${where} order by date desc LIMIT ${(parmse.page - 1) * parmse.size},${parmse.size}`
}
db.all(sql, (err, row) => {
db.all(`select count(id) from ${key} ${where}`, (err, row2) => {
res.total = row2[0]['count(id)'];
res.data = row
callback(res)
})
})
} else {
sql = `select * from ${key}`
db.all(sql, (err, row) => {
res.data = row
callback(res)
})
}
}
// }
// //发送信息给指定用户(传id)
// mydb.prototype.getSendList = (id, callback) => {
// db.all(`select * from sendList where userIds like '%${id}%' `, (err, row) => {
// if (!err) {
// if (callback) callback(row)
// } else {
// if (callback) callback(0)
// }
// })
// }
// // 条件查询
// mydb.prototype.setALL = (callback) => {
// db.exec(`UPDATE History set Type=1 `, (err) => {
// if (!err) {
// if (callback) callback(1)
// } else {
// if (callback) callback(0)
// }
// })
// }
// // callb ack
// //设置数据
// 新增数据
mydb.prototype.add = (key, data, callback) => {
try {
if (key == 'sys') {
var add = db.prepare(`INSERT OR REPLACE INTO ${key} VALUES (?,?,?,?,?,?,?)`);
add.run(genID(), data.wavefiltering, data.threshold, data.area, data.cameraIP,data.computerIP,data.plcIP)
add.finalize(err => {
if (!err) {
if (callback) callback(1)
} else {
if (callback) callback(0)
}
});
} else if (key == "history") {
var add = db.prepare(`INSERT OR REPLACE INTO ${key} VALUES (?,?,?,?,)`);
// console.log('genID()=============>',genID(), nowTime(), data)
add.run(genID(), nowTime(), data.templateImg, data.result)
add.finalize(err => {
if (!err) {
if (callback) callback(1)
} else {
if (callback) callback(0)
}
});
}
else if (key == "template") {
var add = db.prepare(`INSERT OR REPLACE INTO ${key} VALUES (?,?,?,?)`);
// console.log('genID()=============>',genID(), nowTime(), data)
add.run(genID(), data.name, data.status, data.arr)
add.finalize(err => {
if (!err) {
if (callback) callback(1)
} else {
if (callback) callback(0)
}
});
}
} catch (error) {
callback(error)
}
}
// // Object.keys(data).forEach((key) => {
// // // 这里 obj[key] 便是对象的每一个的值
// // if (key != 'id') {
// // str = str + key + '=' + data[key] + ','
// // }
// // })
// // str.substring(0, str.lastIndexOf(','))
// // db.exec(`UPDATE ${key} set ${str} where Id =${data.id}`, (err) => {
// // console.log(err)
// // });
// // db.close()
// }
// // 编辑数据
mydb.prototype.edit = (key, data, callback) => {
var str = ''
Object.keys(data).forEach((key) => {
// 这里 obj[key] 便是对象的每一个的值
if (key != 'id' && data[key]) {
str = str + key + '=' + "'" + data[key] + "'" + ','
}
})
var sql = str.substring(0, str.lastIndexOf(','))
// console.log(`UPDATE ${key} set ${sql} where Id ='${data.Id}'`)
db.exec(`UPDATE ${key} set ${sql} where id='${data.id}'`, (err) => {
if (!err) {
if (callback) callback(1)
} else {
if (callback) callback(0)
}
});
// db.close()
}
// // 删除数据
mydb.prototype.remove = (key, id, callback) => {
db.exec(`DELETE from ${key} where id ='${id}'`, (err) => {
console.log(err)
if (!err) {
if (callback) callback(1)
} else {
if (callback) callback(0)
}
});
// db.close()
}
// // 查询
// mydb.prototype.find = (key, findKey, str) => {
// }
// // 日志
// mydb.prototype.setLog = (text) => {
// db.data.log.push({ ...data, time: new Date().getTime() })
// db.write()
// localStorage.getItem('username')
// }
export default mydb
很久以前简单封装,新增需要根据字段数量与名称进行修改,编辑删除都已封装完成
用法
main.js vue3写法 (vue2 往原型里直接加)
import db from './until/sq3.js'
const app = createApp(App)
app.config.globalProperties.db = new db
已下是在 VUE2 中 具体用法
// 获取列表 qurey为搜索条件
// currentPage: {
// page: 1,
// size: 5,
// },
this.db.get(
"History",
this.currentPage,
(res) => {
this.tableData = [...res.data];
this.total = res.total;
},
this.qurey
);
// 编辑 新增数据
this.db.edit("History", { Id: el.Id, Type: "1" }, (res) => {
if (res) {
this.db.add("Log", {
Name: "日志操作",
UserName: 'admin',
Type: "解除",
Detail: "解除了记录",
});
}
});
随笔记录,sqlite 用了挺久的了 感觉很好用的一个