在 Web 應用方面 MySQL 是最常見,最好的關(guān)系型數(shù)據(jù)庫之一。非常多網(wǎng)站都選擇 MySQL 作為網(wǎng)站數(shù)據(jù)庫。
egg-mysql框架提供了 egg-mysql 插件來訪問 MySQL 數(shù)據(jù)庫。這個插件既可以訪問普通的 MySQL 數(shù)據(jù)庫,也可以訪問基于 MySQL 協(xié)議的在線數(shù)據(jù)庫服務。
安裝與配置安裝對應的插件 egg-mysql :
開啟插件:
// config/plugin.js exports.mysql = { enable: true, package: 'egg-mysql', };
在 config/config.${env}.js 配置各個環(huán)境的數(shù)據(jù)庫連接信息。
單數(shù)據(jù)源如果我們的應用只需要訪問一個 MySQL 數(shù)據(jù)庫實例,可以如下配置:
// config/config.${env}.js exports.mysql = { // 單數(shù)據(jù)庫信息配置 client: { // host host: 'mysql.com', // 端口號 port: '3306', // 用戶名 user: 'test_user', // 密碼 password: 'test_password', // 數(shù)據(jù)庫名 database: 'test', }, // 是否加載到 app 上,默認開啟 app: true, // 是否加載到 agent 上,默認關(guān)閉 agent: false, };
使用方式:
await app.mysql.query(sql, values); // 單實例可以直接通過 app.mysql 訪問
多數(shù)據(jù)源如果我們的應用需要訪問多個 MySQL 數(shù)據(jù)源,可以按照如下配置:
exports.mysql = { clients: { // clientId, 獲取client實例,需要通過 app.mysql.get('clientId') 獲取 db1: { // host host: 'mysql.com', // 端口號 port: '3306', // 用戶名 user: 'test_user', // 密碼 password: 'test_password', // 數(shù)據(jù)庫名 database: 'test', }, db2: { // host host: 'mysql2.com', // 端口號 port: '3307', // 用戶名 user: 'test_user', // 密碼 password: 'test_password', // 數(shù)據(jù)庫名 database: 'test', }, // ... }, // 所有數(shù)據(jù)庫配置的默認值 default: { }, // 是否加載到 app 上,默認開啟 app: true, // 是否加載到 agent 上,默認關(guān)閉 agent: false, };
使用方式:
const client1 = app.mysql.get('db1'); await client1.query(sql, values); const client2 = app.mysql.get('db2'); await client2.query(sql, values);
動態(tài)創(chuàng)建我們可以不需要將配置提前申明在配置文件中,而是在應用運行時動態(tài)的從配置中心獲取實際的參數(shù),再來初始化一個實例。
// {app_root}/app.js module.exports = app => { app.beforeStart(async () => { // 從配置中心獲取 MySQL 的配置 // { host: 'mysql.com', port: '3306', user: 'test_user', password: 'test_password', database: 'test' } const mysqlConfig = await app.configCenter.fetch('mysql'); app.database = app.mysql.createInstance(mysqlConfig); }); };
Service 層由于對 MySQL 數(shù)據(jù)庫的訪問操作屬于 Web 層中的數(shù)據(jù)處理層,因此我們強烈建議將這部分代碼放在 Service 層中維護。
下面是一個 Service 中訪問 MySQL 數(shù)據(jù)庫的例子。
更多 Service 層的介紹,可以參考 Service
// app/service/user.js class UserService extends Service { async find(uid) { // 假如 我們拿到用戶 id 從數(shù)據(jù)庫獲取用戶詳細信息 const user = await this.app.mysql.get('users', { id: 11 }); return { user }; } }
之后可以通過 Controller 獲取 Service 層拿到的數(shù)據(jù)。
// app/controller/user.js class UserController extends Controller { async info() { const ctx = this.ctx; const userId = ctx.params.id; const user = await ctx.service.user.find(userId); ctx.body = user; } }
如何編寫 CRUD 語句下面的語句若沒有特殊注明,默認都書寫在 app/service 下。
Create可以直接使用 insert 方法插入一條記錄。
// 插入 const result = await this.app.mysql.insert('posts', { title: 'Hello World' }); // 在 post 表中,插入 title 為 Hello World 的記錄 => INSERT INTO `posts`(`title`) VALUES('Hello World'); console.log(result); => { fieldCount: 0, affectedRows: 1, insertId: 3710, serverStatus: 2, warningCount: 2, message: '', protocol41: true, changedRows: 0 } // 判斷插入成功 const insertSuccess = result.affectedRows === 1;
Read可以直接使用 get 方法或 select 方法獲取一條或多條記錄。select 方法支持條件查詢與結(jié)果的定制。
const post = await this.app.mysql.get('posts', { id: 12 }); => SELECT * FROM `posts` WHERE `id` = 12 LIMIT 0, 1;
const results = await this.app.mysql.select('posts'); => SELECT * FROM `posts`;
const results = await this.app.mysql.select('posts', { // 搜索 post 表 where: { status: 'draft', author: ['author1', 'author2'] }, // WHERE 條件 columns: ['author', 'title'], // 要查詢的表字段 orders: [['created_at','desc'], ['id','desc']], // 排序方式 limit: 10, // 返回數(shù)據(jù)量 offset: 0, // 數(shù)據(jù)偏移量 }); => SELECT `author`, `title` FROM `posts` WHERE `status` = 'draft' AND `author` IN('author1','author2') ORDER BY `created_at` DESC, `id` DESC LIMIT 0, 10;
Update可以直接使用 update 方法更新數(shù)據(jù)庫記錄。
// 修改數(shù)據(jù),將會根據(jù)主鍵 ID 查找,并更新 const row = { id: 123, name: 'fengmk2', otherField: 'other field value', // any other fields u want to update modifiedAt: this.app.mysql.literals.now, // `now()` on db server }; const result = await this.app.mysql.update('posts', row); // 更新 posts 表中的記錄 => UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE id = 123 ; // 判斷更新成功 const updateSuccess = result.affectedRows === 1; // 如果主鍵是自定義的 ID 名稱,如 custom_id,則需要在 `where` 里面配置 const row = { name: 'fengmk2', otherField: 'other field value', // any other fields u want to update modifiedAt: this.app.mysql.literals.now, // `now()` on db server }; const options = { where: { custom_id: 456 } }; const result = await this.app.mysql.update('posts', row, options); // 更新 posts 表中的記錄 => UPDATE `posts` SET `name` = 'fengmk2', `modifiedAt` = NOW() WHERE custom_id = 456 ; // 判斷更新成功 const updateSuccess = result.affectedRows === 1;
Delete可以直接使用 delete 方法刪除數(shù)據(jù)庫記錄。
const result = await this.app.mysql.delete('posts', { author: 'fengmk2', }); => DELETE FROM `posts` WHERE `author` = 'fengmk2';
直接執(zhí)行 sql 語句插件本身也支持拼接與直接執(zhí)行 sql 語句。使用 query 可以執(zhí)行合法的 sql 語句。
注意!!我們極其不建議開發(fā)者拼接 sql 語句,這樣很容易引起 sql 注入?。?/p>
如果必須要自己拼接 sql 語句,請使用 mysql.escape 方法。
參考 preventing-sql-injection-in-node-js
const postId = 1; const results = await this.app.mysql.query('update posts set hits = (hits + ?) where id = ?', [1, postId]); => update posts set hits = (hits + 1) where id = 1;
使用事務MySQL 事務主要用于處理操作量大,復雜度高的數(shù)據(jù)。比如說,在人員管理系統(tǒng)中,你刪除一個人員,你既需要刪除人員的基本資料,也要刪除和該人員相關(guān)的信息,如信箱,文章等等。這時候使用事務處理可以方便管理這一組操作。 一個事務將一組連續(xù)的數(shù)據(jù)庫操作,放在一個單一的工作單元來執(zhí)行。該組內(nèi)的每個單獨的操作是成功,事務才能成功。如果事務中的任何操作失敗,則整個事務將失敗。
一般來說,事務是必須滿足4個條件(ACID): Atomicity(原子性)、Consistency(一致性)、Isolation(隔離性)、Durability(可靠性)
原子性:確保事務內(nèi)的所有操作都成功完成,否則事務將被中止在故障點,以前的操作將回滾到以前的狀態(tài)。 一致性:對于數(shù)據(jù)庫的修改是一致的。 隔離性:事務是彼此獨立的,不互相影響 持久性:確保提交事務后,事務產(chǎn)生的結(jié)果可以永久存在。 因此,對于一個事務來講,一定伴隨著 beginTransaction、commit 或 rollback,分別代表事務的開始,成功和失敗回滾。
egg-mysql 提供了兩種類型的事務。
手動控制優(yōu)點:beginTransaction, commit 或 rollback 都由開發(fā)者來完全控制,可以做到非常細粒度的控制。 缺點:手寫代碼比較多,不是每個人都能寫好。忘記了捕獲異常和 cleanup 都會導致嚴重 bug。 const conn = await app.mysql.beginTransaction(); // 初始化事務 try { await conn.insert(table, row1); // 第一步操作 await conn.update(table, row2); // 第二步操作 await conn.commit(); // 提交事務 } catch (err) { // error, rollback await conn.rollback(); // 一定記得捕獲異常后回滾事務??! throw err; }
自動控制:Transaction with scopeAPI:beginTransactionScope(scope, ctx)scope: 一個 generatorFunction,在這個函數(shù)里面執(zhí)行這次事務的所有 sql 語句。ctx: 當前請求的上下文對象,傳入 ctx 可以保證即便在出現(xiàn)事務嵌套的情況下,一次請求中同時只有一個激活狀態(tài)的事務。 優(yōu)點:使用簡單,不容易犯錯,就感覺事務不存在的樣子。 缺點:整個事務要么成功,要么失敗,無法做細粒度控制。 const result = await app.mysql.beginTransactionScope(async conn => { // don't commit or rollback by yourself await conn.insert(table, row1); await conn.update(table, row2); return { success: true }; }, ctx); // ctx 是當前請求的上下文,如果是在 service 文件中,可以從 `this.ctx` 獲取到 // if error throw on scope, will auto rollback
表達式(Literal)如果需要調(diào)用 MySQL 內(nèi)置的函數(shù)(或表達式),可以使用 Literal。
內(nèi)置表達式NOW():數(shù)據(jù)庫當前系統(tǒng)時間,通過 app.mysql.literals.now 獲取。 await this.app.mysql.insert(table, { create_time: this.app.mysql.literals.now, }); => INSERT INTO `$table`(`create_time`) VALUES(NOW())
自定義表達式下例展示了如何調(diào)用 MySQL 內(nèi)置的 CONCAT(s1, ...sn) 函數(shù),做字符串拼接。
const Literal = this.app.mysql.literals.Literal; const first = 'James'; const last = 'Bond'; await this.app.mysql.insert(table, { id: 123, fullname: new Literal(`CONCAT("${first}", "${last}"`), }); => INSERT INTO `$table`(`id`, `fullname`) VALUES(123, CONCAT("James", "Bond"))
更多建議: