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');
});
标签:const,nodejs,koa,data,return,table,async,knex
From: https://blog.csdn.net/weixin_52380389/article/details/142654414