Nodejs数据库查询构建器knex的使用

Nodejs数据库查询构建器knex的使用
Knex.js 是一个 SQL 查询构建器,它为 Node.js 环境提供了强大的 SQL 构建功能。你可以用它来生成和执行各种复杂的 SQL 查询。下面我将向你介绍如何安装和使用 Knex。

安装

首先你需要安装 Knex 和你的数据库驱动。例如,如果你正在使用 PostgreSQL,你可以运行以下命令:

npm install knex --save
npm install pg --save

对于 MySQL,你可以这样做:

npm install knex --save
npm install mysql2 --save

配置 Knex

在项目中创建一个文件,比如 knexfile.js 来配置 Knex:

const path = require('path');

module.exports = {

  development: {
    client: 'sqlite3',
    connection: {
      filename: path.join(__dirname, '../db/development.sqlite3'),
    },
    useNullAsDefault: true,
  },

  production: {
    client: 'postgresql',
    connection: process.env.DATABASE_URL,
    pool: { min: 2, max: 10 },
    migrations: {
      tableName: 'knex_migrations'
    }
  }

};

初始化 Knex

在你的应用入口文件(例如 index.jsapp.js)中初始化 Knex:

const knex = require('knex')({
  client: 'sqlite3', // 或者 'pg' for PostgreSQL
  connection: {
    filename: './db/development.sqlite3'
  },
  useNullAsDefault: true
});

// 或者基于环境变量选择不同的配置
const environment = process.env.NODE_ENV || 'development';
const config = require('./knexfile')[environment];
const knex = require('knex')(config);

执行基本查询

插入数据

knex('users').insert({ name: 'John Doe', email: 'john@example.com' })
  .then(id => console.log(id))
  .catch(err => console.error(err));

查询数据

knex('users')
  .select('*')
  .where('email', 'like', '%example.com%')
  .then(rows => console.log(rows))
  .catch(err => console.error(err));

更新数据

knex('users')
  .update({ email: 'newemail@example.com' })
  .where('id', 1)
  .then(() => console.log("Updated"))
  .catch(err => console.error(err));

删除数据

knex('users')
  .del()
  .where('id', 1)
  .then(() => console.log("Deleted"))
  .catch(err => console.error(err));

使用事务

knex.transaction(function (trx) {
  return knex('users')
    .transacting(trx)
    .insert({ name: 'Jane Doe', email: 'jane@example.com' })
    .then(function () {
      return knex('profiles')
        .transacting(trx)
        .insert({ user_id: 2, bio: 'A new user.' });
    })
    .then(trx.commit)
    .catch(trx.rollback);
}).catch(function (err) {
  console.log(err);
});

以上就是 Knex.js 的一些基础用法。通过这些示例,你可以开始构建更复杂的 SQL 查询。


3 回复

Knex.js 是一个非常灵活的 Node.js 查询构建器,它让你可以轻松地与 SQL 数据库交互,而无需直接写复杂的 SQL 语句。想象一下,你正在为你的应用搭建一个梦幻厨房,而 Knex 就是那个超级厨师,他能用简单的食材(代码)做出美味佳肴(查询结果)。

首先,你需要安装 Knex 和相应的数据库驱动,比如 mysqlpg

npm install knex --save
# 安装对应的数据库驱动
npm install mysql --save # 或者 npm install pg

然后,配置 Knex:

const knex = require('knex')({
  client: 'mysql', // 或 'pg'
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

现在你可以开始烹饪了!比如,查询所有用户:

knex('users')
  .select('*')
  .then(users => console.log(users))
  .catch(err => console.error(err));

是不是感觉很简单?Knex 还支持更复杂的操作,比如条件查询、事务管理等,就像是给你的厨房增加了更多的厨具和调料。祝你在编程的世界里烹饪愉快!


Knex.js 是一个SQL查询构建器,支持多种关系型数据库(如PostgreSQL, MySQL, SQLite3等)。下面是一些基本的使用方法:

  1. 安装:首先需要安装 knex 和你的数据库适配器。例如,如果你正在使用 PostgreSQL,你需要运行 npm install knex pg

  2. 创建连接:创建一个 knex 实例,用于与数据库进行通信。

const knex = require('knex')({
  client: 'pg', // 数据库类型
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});
  1. 执行查询:可以使用 Knex 提供的各种方法来构建 SQL 查询。例如,你可以使用 .select() 方法选择列,.from() 方法指定表名,.where() 方法添加条件等。
knex('users')
  .select('name', 'email')
  .where({ id: 1 })
  .then(rows => console.log(rows))
  .catch(err => console.error(err));
  1. 插入数据:可以使用 .insert() 方法插入新行。
knex('users').insert({ name: 'Test User', email: 'test@example.com' })
  .then(ids => console.log(ids))
  .catch(err => console.error(err));
  1. 更新数据:可以使用 .update() 方法更新行。
knex('users').update({ name: 'Updated User' }).where({ id: 1 })
  .then(rowsAffected => console.log(rowsAffected))
  .catch(err => console.error(err));
  1. 删除数据:可以使用 .del().delete() 方法删除行。
knex('users').del().where({ id: 1 })
  .then(rowsDeleted => console.log(rowsDeleted))
  .catch(err => console.error(err));

注意,所有的操作都是异步的,所以你需要使用 .then() 或者 async/await 来处理返回的结果或错误。

Knex.js 是一个 SQL 查询构建器,用于 Node.js 环境。首先,你需要通过 npm 安装 knex 和相应的数据库驱动。例如,对于 MySQL:

npm install knex mysql

配置 knex:

const knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

使用示例:

knex('users').select('*').where({ id: 1 }).then(rows => console.log(rows));

这将选择 users 表中 id 为 1 的记录。

回到顶部