1、安裝egg-mysql
npm i egg-mysql --save
2、配置插件
// config/plugin.js
'use strict';
exports.mysql = {
enable: true,
package: 'egg-mysql',
};
3、數據庫連接配置
// config/config.default.js
'use strict';
module.exports = appInfo => {
const config = exports = {};
config.mysql = {
client: {
host: 'localhost',
port: '3306',
user: 'root',
password: '123456',
database: 'test',
},
app: true, // 是否加載到 app 上,默認開啟
agent: false, // 是否加載到 agent 上,默認關閉
};
return {
...config
};
};
4、增、刪、改、查操作
//查詢一條數據,提到一個json對象{}
let result = await this.app.mysql.get("user",{id:1});
//查詢多條數據,返回一個json數組[]
let result = await this.app.mysql.select(
"user",
{
where:{id:1}
}
);
//追加數據記錄
let result = await this.app.mysql.insert(
"user",
{username:"lisi",password:"1234"}
);
//更新數據 (按主鍵進行更新)
let result = await this.app.mysql.update('user',{ id:2, username:'趙四' });
//更新數據 通過 sql 語句
let results=await this.app.mysql.query(
'update user set username = ? where id = ?',
["王五",2]
);
//刪除數據
let result= await this.app.mysql.delete('user',{ id:3 });
//執行SQL
this.app.mysql.query(sql,values);
5、事務處理
var conn = await this.app.mysql.beginTransaction();
try{
await conn.query("delete from fee_borrow_bill where borrow_bill_code=?",[borrow_bill_code]);
await conn.query("delete from fee_borrow_bill_item where borrow_bill_code=?",[borrow_bill_code]);
await conn.commit();
return "ok";
}catch(err){
await conn.rollback();
return "數據庫操作異常,請聯系管理員! ";
}
6、多數據庫操作
// 配置
exports.mysql = {
clients: {
db1: {
host: 'mysql.com',
port: '3306',
user: 'test_user',
password: 'test_password',
database: 'test',
},
// ...
},
// default configuration for all databases
default: {
},
// load into app, default is open
app: true,
// load into agent, default is close
agent: false,
};
//使用
const client1 = app.mysql.get('db1');
client1.query(sql, values);
const client2 = app.mysql.get('db2');
client2.query(sql, values);