您当前的位置: 首页 >  ui

彭世瑜

暂无认证

  • 3浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

彭世瑜 发布时间:2022-08-15 16:12:24 ,浏览量:3

文档:

  • github https://github.com/knex/knex
  • 官网 https://knexjs.org/
  • npmjs https://npmjs.com/package/knex

安装

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();

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.3138s