elctron 使用node模块记录之sqlite3

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 用了挺久的了 感觉很好用的一个

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQLite3是一个轻量级的关系型数据库管理系统,在Python中内置了SQLite3的模块,可以通过该模块来连接和操作SQLite3数据库使用SQLite3模块的流程如下: 1. 导入SQLite3模块使用`import sqlite3`语句导入SQLite3模块。 2. 连接到数据库使用`sqlite3.connect()`方法连接到SQLite3数据库。该方法接受一个参数,即数据库文件的路径,如果该文件不存在,则会自动创建一个。 3. 创建游标对象:使用`connection.cursor()`方法创建一个游标对象,该对象可以用于执行SQL语句和获取查询结果。 4. 执行SQL语句:使用游标对象的`execute()`方法执行SQL语句。该方法接受一个SQL语句作为参数,并返回一个查询结果集或执行结果。 5. 提交事务:如果执行的是修改数据库的操作,需要使用`connection.commit()`方法提交事务。 6. 关闭游标对象和数据库连接:使用`cursor.close()`方法关闭游标对象,使用`connection.close()`方法关闭数据库连接。 下面是一个简单的示例代码: ```python import sqlite3 # 连接到数据库 conn = sqlite3.connect('test.db') # 创建游标对象 cursor = conn.cursor() # 执行SQL语句 cursor.execute('CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)') # 提交事务 conn.commit() # 关闭游标对象和数据库连接 cursor.close() conn.close() ``` 以上代码连接到`test.db`数据库,并创建了一个名为`user`的表,该表包含`id`、`name`和`age`三个字段。在执行完SQL语句后,需要调用`commit()`方法提交事务,并关闭游标对象和数据库连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值