Nodejs 第三十九章(knex)

knex

Knex是一个基于JavaScript的查询生成器,它允许你使用JavaScript代码来生成和执行SQL查询语句。它提供了一种简单和直观的方式来与关系型数据库进行交互,而无需直接编写SQL语句。你可以使用Knex定义表结构、执行查询、插入、更新和删除数据等操作。

knexjs.org/guide/query...

Knex的安装和设置

knex支持多种数据库 pg sqlite3 mysql2 oracledb tedious

用什么数据库安装对应的数据库就行了

sh 复制代码
#安装knex
$ npm install knex --save

#安装你用的数据库
$ npm install pg
$ npm install pg-native
$ npm install sqlite3
$ npm install better-sqlite3
$ npm install mysql
$ npm install mysql2
$ npm install oracledb
$ npm install tedious

连接数据库

js 复制代码
import knex from 'knex'
const db = knex({
    client: "mysql2",
    connection: config.db
})
yaml 复制代码
db:
  user: root
  password: '123456'
  host: localhost
  port: 3306
  database: xiaoman

定义表结构

js 复制代码
db.schema.createTable('list', (table) => {
    table.increments('id') //id自增
    table.integer('age') //age 整数
    table.string('name') //name 字符串
    table.string('hobby') //hobby 字符串
    table.timestamps(true,true) //创建时间和更新时间
}).then(() => {
    console.log('创建成功')
})

实现增删改差

js 复制代码
import mysql2 from 'mysql2/promise'
import fs from 'node:fs'
import jsyaml from 'js-yaml'
import express from 'express'
import knex from 'knex'
const yaml = fs.readFileSync('./db.config.yaml', 'utf8')
const config = jsyaml.load(yaml)
// const sql = await mysql2.createConnection({
//    ...config.db
// })
const db = knex({
    client: "mysql2",
    connection: config.db
})

const app = express()
app.use(express.json())
//查询接口 全部
app.get('/', async (req, res) => {
    const data = await db('list').select().orderBy('id', 'desc')
    const total = await db('list').count('* as total')
    res.json({
        code: 200,
        data,
        total: total[0].total,
    })
})
//单个查询 params
app.get('/user/:id', async (req, res) => {
    const row = await db('list').select().where({ id: req.params.id })
    res.json({
        code: 200,
        data: row
    })
})

//新增接口
app.post('/create', async (req, res) => {
    const { name, age, hobby } = req.body
    const detail = await db('list').insert({ name, age, hobby })
    res.send({
        code: 200,
        data: detail
    })
})

//编辑
app.post('/update', async (req, res) => {
    const { name, age, hobby, id } = req.body
    const info = await db('list').update({ name, age, hobby }).where({ id })
    res.json({
        code: 200,
        data: info
    })
})
//删除
app.post('/delete', async (req, res) => {
    const info = await db('list').delete().where({ id: req.body.id })
    res.json({
        code: 200,
        data: info
    })
})
const port = 3000

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

事务

你可以使用事务来确保一组数据库操作的原子性,即要么全部成功提交,要么全部回滚

例如A给B转钱,需要两条语句,如果A语句成功了,B语句因为一些场景失败了,那这钱就丢了,所以事务就是为了解决这个问题,要么都成功,要么都回滚,保证金钱不会丢失。

js 复制代码
//伪代码
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 (err) {
        await trx.rollback() //回滚事务
    }
   
})
相关推荐
小徐不会敲代码~3 分钟前
Vue3 学习
前端·javascript·vue.js·学习
大猩猩X5 分钟前
vue vxe-gantt table 甘特图实现多个维度视图展示,支持切换年视图、月视图、周视图等
前端·javascript·甘特图·vxe-table·vxe-ui
m0_740043736 分钟前
Element-UI 组件库的核心组件及其用法
前端·javascript·vue.js·ui·elementui·html
向上的车轮10 分钟前
从“能用”到“好用”:基于 DevUI 构建高维护性、多端自适应的企业级前端架构实践
前端·架构
脾气有点小暴21 分钟前
H5 跳转方式
前端·javascript
ghfdgbg24 分钟前
11. 后端Web实战:登录认证(令牌 + 过滤器 + 拦截器)
前端
Doris89330 分钟前
【JS】JS进阶--作用域、函数、解构赋值、数组方法
开发语言·前端·javascript
黑客思维者31 分钟前
核弹级漏洞突袭React生态:RSC反序列化何以成为RCE通道?
前端·javascript·react.js·远程代码执行漏洞