knex.js
一个灵活、便携、有趣的 SQL 查询构建器!
一个功能齐全的、多语言(MSSQL、MySQL、PostgreSQL、SQLite3、Oracle(包括 Oracle Wallet 认证))的 Node.js 查询构建器,其特点是:
支持Node.js 10+版本。
阅读完整的文档以开始使用!
或者查看我们的 Recipes wiki 来搜索一些特定问题的解决方案。
如果从旧版本升级,请参见 升级说明。
如需支持和提问,请加入 freenode IRC 的 #bookshelf 频道。
关于对象关系映射器,请看。
要查看 Knex 将为给定查询生成的 SQL,请看:Knex 查询实验室
例子
我们在网站上有几个例子。这里是第一个让你入门的例子:
const knex = require('knex')({ client: 'sqlite3', connection: { filename: './data.db', }, }); // Create a table knex.schema .createTable('users', table => { table.increments('id'); table.string('user_name'); }) // ...and another .createTable('accounts', table => { table.increments('id'); table.string('account_name'); table .integer('user_id') .unsigned() .references('users.id'); }) // Then query the table... .then(() => knex('users').insert({ user_name: 'Tim' }) ) // ...and using the insert id, insert into the other table. .then(rows => knex('accounts').insert({ account_name: 'knex', user_id: rows[0] }) ) // Query both of the rows. .then(() => knex('users') .join('accounts', 'users.id', 'accounts.user_id') .select('users.user_name as user', 'accounts.account_name as account') ) // map over the results .then(rows => rows.map(row => { console.log(row) }) ) // Finally, add a .catch handler for the promise chain .catch(e => { console.error(e); });