zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Node.js:knex.js数据库MySQL query builder

mysqlJS数据库Node Query Builder
2023-09-14 09:07:16 时间

文档:

安装

pnpm install knex mysql2 --save

使用示例

数据表

CREATE TABLE `table_user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(20)  NOT NULL,
  `age` int NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

连接数据库

import knex from "knex";

// 连接数据库
const query = knex({
  client: "mysql2",
  connection: {
    host: "127.0.0.1",
    port: 3306,
    user: "root",
    password: "123456",
    database: "data",
  },
});

// 断开连接
await query.destroy()

基本的CURD

// 插入数据
let result = await query("table_user").insert({
  name: "Tom",
  age: 23,
});

console.log(result[0]); // 获取插入的id


// 读取数据
let result = await query("table_user").select(["name", "age"]);

console.log(result);
// [ { name: 'Tom', age: 23 }, { name: 'Tom', age: 23 } ]

// 更新数据
await query("table_user")
  .where({
    id: 1,
  })
  .update({
    name: "Jack",
  });

// 删除数据
await query("table_user")
  .where({
    id: 1,
  })
  .delete();