【Node.js】knex 操作 MySQL 数据库

js 复制代码
db:
  user: root
  password: 'root'
  host: localhost
  port: 3306
  database: my_db_01

基本操作

js 复制代码
import express from "express";
import fs from "fs";
// import mysql2 from "mysql2/promise";
import jsyaml from 'js-yaml';
import knex from 'knex'

const app = express()
app.use(express.json())
const yaml = fs.readFileSync('./db.config.yaml', 'utf8')
// 将yaml 解析为一个对象
const config = jsyaml.load(yaml)
// console.log(config)
// mysql2.createConnection({
//     host: 'localhost',
//     user: 'root',
//     password: 'root',
//     database: 'my_db_01'
// })
// const sql = await mysql2.createConnection({
//     ...config.db
// })
const db = knex({
    client: 'mysql2',
    connection: config.db
})
//创建表
db.schema.createTableIfNotExists('list', table => {
    table.increments('id');//主键 自增
    table.integer('age')
    table.string('name')
    table.string('hobby')
    table.timestamps(true, true)  //创建时间 更新时间
}).then(() => {
    console.log('创建成功')
})
//查询全部
app.get('/', async (req, res) => {
    // const [data] = await sql.query('select * from user')
    const data = await db('list').select()
    //db('list').select().toSQL().sql knex也可以反编译为 sql 语句进行调试
    // 同时也支持 直接使用sql 语句
    // db.raw('select * from list').then((data)=> {
    //     console.log(data)
    // })
    const count = await db('list').count("* as total") // [{total: 1}]
    // res.send(data)
    res.json({
        data,
        total: count[0].total
    })
})
//单个查询
app.get('/user/:id', async (req, res) => {
    // const [data]  = await sql.query(`// select * from user where id=${req.params.id}`) //两种写法
    // const [data] = await sql.query(`select * from user where id = ?`, [req.params.id])
    const data = await db('list').select().where({id: req.params.id})
    res.send(data)
})
//新增接口
app.post('/create', async (req, res) => {
    const {name, age, hobby} = req.body
    // await sql.query(`insert into user(NAME, AGE, ADDRESS) values(?,?,?)`, [name, age, address])
    await db('list').insert({name, age, hobby})
    res.send({ok: 1})
})
//编辑
app.post('/update', async (req, res) => {
    const {name, age, hobby, id} = req.body
    // await sql.query(`update user set NAME=?, AGE=?, ADDRESS=? where id=?`,[name, age, address,id])
    await db('list').update({name, age, hobby}).where({id})
    res.send({ok: 1})
})
//删除
app.post('/delete', async (req, res) => {
    // const {id} = req.body
    // await sql.query(`delete from user where id=?`, [id])
    await db('list').delete().where({id: req.body.id})
    res.send({ok: 1})
})
app.listen(3000, () => {
    console.log('3000端口服务端已启动')
})

事务

js 复制代码
// a 给 b 100块钱, a 减少100 的同时 b会增加 100
// 事务保证原子的一致性 要么都成功 要么都回滚
db.transaction(async trx => {
    try {
        await trx('list').update({money: -100}).where({id: 1}) // a
        await trx('list').update({money: +100}).where({id: 2}) // b
        await trx.commit()  // 提交事务
    } catch (e) {
        await trx.rollback() // 回滚事务
    }
}).then(() => {
    console.log('成功')
}).catch(() => {
    console.log('失败')
})
相关推荐
计算机学姐4 分钟前
基于PHP的电脑线上销售系统
开发语言·vscode·后端·mysql·编辑器·php·phpstorm
小光学长19 分钟前
基于vue框架的宠物寻回小程序8g7el(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
数据库
一叶飘零_sweeeet21 分钟前
深入理解 MySQL MVCC:多版本并发控制的核心机制
数据库·mysql
中文很快乐30 分钟前
springboot结合p6spy进行SQL监控
java·数据库·sql
小电玩32 分钟前
谈谈你对Spring的理解
java·数据库·spring
小光学长37 分钟前
基于flask+vue框架的传染病防控酒店信息系统zvt93(程序+源码+数据库+调试部署+开发环境)系统界面在最后面。
数据库
M-bao1 小时前
1000w条数据插入mysql如何设计?
数据库·mysql
666786661 小时前
Mysql高级篇(中)—— SQL优化
linux·运维·服务器·数据库·sql·mysql
十年人间~1 小时前
mysql等保数据库命令
数据库·mysql
翔云API1 小时前
人证合一接口:智能化身份认证的最佳选择
大数据·开发语言·node.js·ocr·php