nodejs koa 用knex.js链接mysql数据库,进行数据增删改查

1、knex.js安装

npm install knex

官方Installation | Knex.js中文文档 | Knex.js中文网

2、进行数据库链接

const knex = require('knex')({
    client: 'mysql2', 
    connection: {
        host: '127.0.0.1', // 地址
        user: 'root', // 账号
        password: '123456', // 密码
        database: 'demo', // 数据库
        options: {
           port: 3306 // 端口
        }
    }
});

3、封装增删改查方法

const knex = require('knex')({
    client: 'mysql2', 
    connection: {
        host: '127.0.0.1', // 地址
        user: 'root', // 账号
        password: '123456', // 密码
        database: 'demo', // 数据库
        options: {
           port: 3306 // 端口
        }
    }
});

// 增加
const create = async (table, data) => {
  return knex(table).insert(data, '*');
};

 
// 更新
const update = async (table, id, data) => {
  return knex(table)
    .where({ id })
    .update(data);
};

// 查询
const find = async (table, condition) => {
    return knex(table).where(condition);
  }
 
// 删除
const remove = async (table, id) => {
  return knex(table)
    .where({ id })
    .del();
};
// 批量新增

const batchInsert = async (table, data) => {
  return knex.batchInsert(table, data)
}

// 批量删除
const batchDelete = async (table, ids) => {
  return knex(table).whereIn('id', ids).del()
}

// 导出
module.exports = {
  create,
  update,
  remove,
  find,
  batchInsert,
  batchDelete,
  knex
};

4、在app.js中引入

onst Koa = require('koa');
const Router = require('koa-router');
const db = require('../config/knex')
// 创建Koa应用实例
const app = new Koa();
 
// 创建路由实例
const router = new Router();
 
// 定义接口路由
    // 增加
    router.post('/api/user/add', async (ctx) => {
       const { username, password, mobile } = ctx.request.body
       try {
            const result = await db.create({
                username,
                password,
                mobile, 
             }) 
            ctx.body = { msg: '新增成功',code: 200 }
        } catch (error) { 
            ctx.body = { msg: '新增失败',code: 400 }
        }
     });
     
 
// 使用路由中间件
app.use(router.routes());
app.use(router.allowedMethods());
 
// 启动服务
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值