db:
user: root
password: 'root'
host: localhost
port: 3306
database: my_db_01
基本操作
import express from "express";
import fs from "fs";
import jsyaml from 'js-yaml';
import knex from 'knex'
const app = express()
app.use(express.json())
const yaml = fs.readFileSync('./db.config.yaml', 'utf8')
const config = jsyaml.load(yaml)
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 db('list').select()
const count = await db('list').count("* as total")
res.json({
data,
total: count[0].total
})
})
app.get('/user/:id', async (req, res) => {
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 db('list').insert({name, age, hobby})
res.send({ok: 1})
})
app.post('/update', async (req, res) => {
const {name, age, hobby, id} = req.body
await db('list').update({name, age, hobby}).where({id})
res.send({ok: 1})
})
app.post('/delete', async (req, res) => {
await db('list').delete().where({id: req.body.id})
res.send({ok: 1})
})
app.listen(3000, () => {
console.log('3000端口服务端已启动')
})
事务
db.transaction(async trx => {
try {
await trx('list').update({money: -100}).where({id: 1})
await trx('list').update({money: +100}).where({id: 2})
await trx.commit()
} catch (e) {
await trx.rollback()
}
}).then(() => {
console.log('成功')
}).catch(() => {
console.log('失败')
})