yu-mysql

2.0.1 • Public • Published

安装

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)

查询sql

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'])

插入sql

const datas=[
    {name: 'yu', telephone: '12345678910'},
    {name: 'yu2', telephone: '12345678910'}
]
//返回值示例:ret=1
const ret = await m.insert('tablename', ...datas)

更新sql

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)

删除sql

//删除id为1的数据
//返回值示例:ret=1
const ret = await m.delete('tablename', `id='1'`)

Dependents (0)

Package Sidebar

Install

npm i yu-mysql

Weekly Downloads

1

Version

2.0.1

License

ISC

Unpacked Size

8.67 kB

Total Files

3

Last publish

Collaborators

  • yuxiaohu90