electron-vue 开发(6) electron使用better-sqlite3插件-2

2,914 阅读1分钟

前言

上一篇说到了如何在electron5.x环境下编译出better-sqlite3插件,那么这一篇就分享一下如何去使用better-sqlite3插件。

better-sqlite3 官方的文档真的是不忍直视,我结合我所使用到的简单的功能做一下总结吧。

创建数据库

this.db = new Database("foobar.db");
try {
  this.db.exec(
    `CREATE TABLE  Photo (
        id    integer primary	 key AUTOINCREMENT,
        photo_path  text,
        is_detect bool,
        detect_status  int,
        desc text,
        time timestamp)`
  );
} catch (error) {
  console.log(error);
  if (error.message == "table Photo already exists") {
    console.log("Photo表已经存在");
  }
}

写入数据

const insert = this.db.prepare(
        "INSERT INTO Photo (photo_path, is_detect, detect_status, time) " +
          "VALUES (@photo_path, @is_detect, @detect_status, @time)"
      );
const insertMany = this.db.transaction((cats) => {
        for (const cat of cats) {
          insert.run(cat);
        }
      });
      insertMany(arr_photo_path);

当然这个插入语句也可以一条一条执行,但是如果按照上述这种写法,应该是走的sqlite事务的功能,写入数据速度会快上很多(它的这个设计语法真的很奇怪...)

查询数据

const stmt = this.db.prepare(
        "select * from Photo where is_detect=0 limit 0,1;"
      );
let obj_photo = stmt.get();

这里obj_photo得到的就是查询的结果,已经转换成了对象。

修改数据

const update = this.db.prepare(
        "update Photo set is_detect=? where id=?;"
      );
update.run(1, 1);

删除数据

 this.db.exec(
                "delete from Photo;update sqlite_sequence SET seq = 0 where name ='Photo';"
              );

总结

好的,至此就已经做完了基本的数据库的增删改查的功能。此外我发现better-sqlite3的函数都是同步执行的,这样也方便了一些逻辑的编写,也是挺方便的。如果想要异步的话,放在回调函数里面执行应该也是可以的。