安装
npm i sqlite3 sqlite -s
//sqlite3为sqlite数据库驱动
//sqlite库:使用了promise对sqlite3 进行一次封装,比回调方式更符合我们的操作
连接数据库
新建 dbConnect.js 文件
const { open } = require("sqlite");
const sqlite3 = require("sqlite3").verbose();
//dbPath为你想存放数据库文件的目录路径
const connectDb = (dbPath) => {
return open({
filename: dbPath,
driver: sqlite3.Database,
});
};
module.exports = { connectDb };
连接数据库并建立一个表
//引入
const { connectDb } = require("./db/index");
//自定义数据库路径
const userDbPath = path.join("./db", "user.db");
async createUserInfoTable() {
const userInfoDb = await connectDb(userDbPath);
const sql = `create table userInfo (
id integer primary key autoincrement ,
username varchar unique not null ,
password varchar not null ,
name text not null ,
remark text
)`;
let res = null;
try {
//查询使用userInfoDb.get userInfoDb.all等 更多命令请查阅官方文档
const runRes = await userInfoDb.run(sql);
res = {
code:200,
data:runRes
}
} catch (e) {
res = {
code:500,
msg:e
}
} finally {
//最后关闭连接
await userInfoDb.close();
}
return res;
}
插入数据
const md5 = require("md5-node");
async inertUserInfoTable(data = {}) {
const userInfoDb = await connectDb(userDbPath);
const sql = `insert into userInfo (username,password,name,remark) values (:username,:password,:name,:remark)`;
let res = null;
try {
const v = {
":username": data[":username"],
":name": data[":name"],
":remark": data[":password"],
":password": md5(data[":password"]),
};
const runRes = await userInfoDb.run(sql, v);
res = {
code:200,
data:runRes
}
} catch (e) {
res = {
code:500,
msg:e
}
} finally {
await userInfoDb.close();
}
return res;
}
作者:Jeebiz 创建时间:2023-07-07 20:21
最后编辑:Jeebiz 更新时间:2024-10-29 20:36
最后编辑:Jeebiz 更新时间:2024-10-29 20:36