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

文档:

安装

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 table = knex({
    
    
  client: "mysql2",
  connection: {
    
    
    host: "127.0.0.1",
    port: 3306,
    user: "root",
    password: "123456",
    database: "data",
  },
});

基本的CURD

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

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

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

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

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

猜你喜欢

转载自blog.csdn.net/mouday/article/details/126348914