Skip to content

Node.js Knex.js 查询生成器

Knex 是一个基于 JavaScript 的 SQL 查询生成器,用代码生成 SQL,避免手写 SQL 字符串。支持 mysql2 / pg / sqlite3 等多种数据库。

bash
npm install knex mysql2

连接数据库

js
import knex from 'knex'

const db = knex({
  client: 'mysql2',           // 数据库驱动
  connection: config.db       // 连接信息(host/port/user等)
})

定义表结构

js
db.schema.createTable('list', (table) => {
  table.increments('id')            // id 自增主键
  table.integer('age')              // 整数
  table.string('name')              // 字符串
  table.string('hobby')
  table.timestamps(true, true)      // created_at / updated_at
}).then(() => console.log('创建成功'))

CRUD 操作(对比 mysql2)

操作mysql2 原写法Knex 链式写法
查全部sql.query('select * from user')db('list').select()
查单个sql.query('...where id = ?', [id])db('list').select().where({id})
新增sql.query('insert into ...values(?,?,?)', [...])db('list').insert({name, age})
更新sql.query('update ...set...where...', [...])db('list').update({name}).where({id})
删除sql.query('delete from...where...', [...])db('list').delete().where({id})
js
// 查询 + 排序 + 总数
const data = await db('list').select().orderBy('id', 'desc')
const total = await db('list').count('* as total')  // [{ total: 10 }]

// 单个查询
const row = await db('list').select().where({ id: req.params.id })

// 新增
await db('list').insert({ name, age, hobby })

// 更新
await db('list').update({ name, age, hobby }).where({ id })

// 删除
await db('list').delete().where({ id: req.body.id })

事务

确保一组操作要么全部成功,要么全部回滚(如转账):

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()  // 回滚
  }
})

Knex vs 原生 SQL

原生 mysql2Knex
写法手写 SQL 字符串链式调用 JS 方法
可读性一般高(链式语义化)
SQL 注入需手动用 ? 占位自动参数化
跨数据库不支持支持(换 client 即可)
建表手写 DDLschema.createTable