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
| 原生 mysql2 | Knex | |
|---|---|---|
| 写法 | 手写 SQL 字符串 | 链式调用 JS 方法 |
| 可读性 | 一般 | 高(链式语义化) |
| SQL 注入 | 需手动用 ? 占位 | 自动参数化 |
| 跨数据库 | 不支持 | 支持(换 client 即可) |
| 建表 | 手写 DDL | schema.createTable |