npm install yu-mysql
const m = require('yu-mysql')
// 数据库配置
const config = {
host: "your host", //(必选)替换成你的host
user: "root", //(必选)替换成你的user
password: "your password", //(必选)替换成你的password
database: "your database", //(必选)替换成你的database
port: 3306, //(非必选)默认3306
charset: "utf8mb4", //(非必选)默认utf8mb4
timezone: "+08:00" //(非必选)默认+08:00
}
//m.init(config)需在首次调用数据库操作之前调用一次即可
//随后跨模块操作数据库可不再调用本方法
//建议在程序入口模块优先调用一次
m.init(config)
const sqls = [
"select * from table",
"insert into table(name) values('yu')",
"update table set name='yu'",
"delete from table where id=1"
]
//update、insert、delete返回的是rows.affectedRows,select返回的是查询结果数组
//select 的时间数据将被格式化为'YYYY-MM-DD HH:mm:ss'
//返回值示例:retArr=[[{name: 'yu'}, {name: 'yu2'}], 1, 1, 0]
const retArr = await m.transaction(...sqls)
const sql = "select * from table"
//返回值示例:ret=[{name: 'yu',telephone:'12345678910'}, {name: 'yu2',telephone:'12345678910'}]
const ret = await m.select(sql)
//返回值示例:ret=[{name: 'yu'}, {name: 'yu2'}]
const ret = await m.select(sql, ['telephone'])
const datas=[
{name: 'yu', telephone: '12345678910'},
{name: 'yu2', telephone: '12345678910'}
]
//返回值示例:ret=1
const ret = await m.insert('tablename', ...datas)
const datas=[
{id: 1, name: 'yu', telephone: '12345678910'},
{id: 2, name: 'yu2', telephone: '12345678910'}
]
//将id为1的name改为yu,telephone改为12345678910
//将id为2的name改为yu2,telephone改为12345678910
//返回值示例:ret=1
const ret = await m.update('tablename', 'id', ...datas)
//删除id为1的数据
//返回值示例:ret=1
const ret = await m.delete('tablename', `id='1'`)