此類封裝了幾個經常使用的方法:插入,更新,刪除,查詢,開啓事務,事務提交,事務回滾等操做。有一這個類,操做MYSQL就方便多了。java
批處理,存儲過程等方法尚未添加,由於以爲目前寫的那裏尚未用到批處理的,因此就沒有在這裏加上,等之後要是用到了要進行批處理的時候,再加上。node
之前用C#在操做數據庫的時候,也都有相似的操做類:MSSQLHelper,OracleHelper,MySQLHelper等這些,如今只是用NodeJs寫了一個操做MySql,想操做其它數據庫,按照這樣的思路也應該能夠寫出來吧。mysql
具體怎麼用在之後再講了,若是心急的話,能夠到個人 github(https://github.com/xiaotuni/angular-map-http2)裏下載項目,運行起來就能夠了。git
const mysql = require('mysql');
/** * 操做類型,插入,更新,刪除,查詢 */
const OperatorType = {
Insert: 0,
Update: 1,
Delete: 2,
QueryList: 3,
QueryOne: 4,
}
/** * 數據操做類 * QueryOne、Query、InsertSQL、DeleteSQL、UpdateSQL、BeginTransaction、Rollback、Commit * * @class MySqlHelper */
class MySqlHelper {
constructor() {
this.__CreatePool();
}
/** * 建立一個資源池 * * @memberof MySqlHelper */
__CreatePool() {
this.pool = mysql.createPool({
connectionLimit: 10,
host: 'localhost', // 數據庫鏈接
user: 'liaohb', // 數據庫名用戶名
password: 'xiaotuni', // 密碼
database: 'nodejs' // 表空間
});
}
/** * 資源池信息 * * @param {any} error 出錯事件出得函數 * @returns * @memberof MySqlHelper */
poolInfo(error) {
if (!this.pool) {
this.__CreatePool();
}
if (!this.pool) {
error && error({ code: 500, msg: '數據庫鏈接失敗' });
return null;
}
return this.pool;
}
/** * 插入操做 * * @param {any} sql 插入語句 * @param {any} success 成功後調用的方法 * @param {any} error 失敗後調用的方法 * @memberof MySqlHelper */
Query(sql, success, error) {
this.__ExecuteSQL(sql, success, error, OperatorType.QueryList);
}
/** * 查詢操做,獲取一條語句 * * @param {any} sql 插入語句 * @param {any} success 成功後調用的方法 * @param {any} error 失敗後調用的方法 * @memberof MySqlHelper */
QueryOne(sql, success, error) {
this.__ExecuteSQL(sql, success, error, OperatorType.QueryOne);
}
/** * 更新操做 * * @param {any} Sql 修改語句 * @param {any} Success 成功後調用的方法 * @param {any} Error 失敗後調用的方法 * @memberof MySqlHelper */
UpdateSQL(Sql, Success, Error) {
this.__ExecuteSQL(Sql, Success, Error, OperatorType.Update);
}
/** * 插入操做 * * @param {any} Sql 插入語句 * @param {any} Success 成功後調用的方法 * @param {any} Error 失敗後調用的方法 * @memberof MySqlHelper */
InsertSQL(Sql, Success, Error) {
this.__ExecuteSQL(Sql, Success, Error, OperatorType.Insert);
}
/** * 刪除操做 * * @param {any} Sql 刪除語句 * @param {any} Success 成功後調用的方法 * @param {any} Error 失敗後調用的方法 * @memberof MySqlHelper */
DeleteSQL(Sql, Success, Error) {
this.__ExecuteSQL(Sql, Success, Error, OperatorType.Delete);
}
/** * 執行SQL語句 * * @param {any} Sql SQL語句 * @param {any} Success 成功後調用的方法 * @param {any} Error 失敗後調用的方法 * @param {any} Type 類型[查詢,更新,刪除,修改等] * @returns * @memberof MySqlHelper */
__ExecuteSQL(Sql, Success, Error, Type) {
const __self = this;
const __ProcessResult = (__sql, result, fields, Type) => {
const _type = Type || OperatorType.QueryOne;
let __result = result;
switch (Type) {
case OperatorType.Insert:
const { insertId } = result;
__result = { insertId };
break;
case OperatorType.Delete:
break;
case OperatorType.Update:
break;
case OperatorType.QueryList:
break;
case OperatorType.QueryOne:
__result = result && result.length > 0 ? result[0] : null;
break;
}
return __result;
};
const { IsBeginTrConn, BeginTrConn } = this;
if (!!IsBeginTrConn) {
console.log('事務線程ID:', BeginTrConn.threadId);
// 事務處理
BeginTrConn.query(Sql, (err, result, fields) => {
if (err) {
__self.Rollback(err);
Error && Error(err);
return;
}
const __result = __ProcessResult(Sql, result, fields, Type);
Success && Success({ fields, result: __result });
});
} else {
const poolInfo = this.poolInfo(Error);
if (!poolInfo) {
return;
}
const __query = poolInfo.query(Sql, (err, result, fields) => {
if (err) {
Error && Error(err);
return;
}
const __result = __ProcessResult(__query.sql, result, fields, Type);
Success && Success({ fields, result: __result });
});
}
}
/** * 開啓事務 * * @param {any} Success 成功後調用的方法 * @param {any} Error 失敗後調用的方法 * @returns * @memberof MySqlHelper */
BeginTransaction(Success, Error) {
const poolInfo = this.poolInfo(Error);
if (!poolInfo) {
return;
}
const __self = this;
poolInfo.getConnection((err, conn) => {
if (err) {
Error && Error(err);
}
conn.beginTransaction((btErr) => {
if (btErr) {
Error && Error(btErr);
}
console.log('開始事務處理...');
__self.BeginTrConn = conn;
__self.IsBeginTrConn = true;
Success && Success();
});
});
}
/** * 事務回滾 * * @param {any} ErrorInfo 回滾出錯信息 * @returns * @memberof MySqlHelper */
Rollback(ErrorInfo) {
const { IsBeginTrConn, BeginTrConn } = this;
const __self = this;
if (!IsBeginTrConn) {
return;
}
if (!BeginTrConn) {
return;
}
console.log('Rollback->事務線程ID:', BeginTrConn.threadId);
BeginTrConn.rollback(() => {
console.log('事務回滾,回滾緣由:', ErrorInfo);
delete __self.IsBeginTrConn;
delete __self.BeginTrConn;
});
}
/** * 提交事件 * * @param {any} Success 成功後調用的方法 * @param {any} Error 失敗後調用的方法 * @returns * @memberof MySqlHelper */
Commit(Success, Error) {
const { IsBeginTrConn, BeginTrConn } = this;
const __self = this;
if (!IsBeginTrConn) {
return;
}
if (!BeginTrConn) {
return;
}
BeginTrConn.commit((err) => {
if (err) {
console.log('事務提交失敗,執行回滾操做...');
__self.Rollback(err);
Error && Error(err);
return;
}
console.log('事務提交成功...');
console.log('Commit->事務提交成功...事務ID:', BeginTrConn.threadId);
delete __self.IsBeginTrConn;
delete __self.BeginTrConn;
Success && Success();
});
}
/** * 關閉鏈接池 * * @param {any} Success * @param {any} Error * @returns * @memberof MySqlHelper */
ClosePool(Success, Error) {
const __self = this;
const poolInfo = this.poolInfo(Error);
if (!poolInfo) {
return;
}
poolInfo.end((err) => {
if (err) {
Error && Error(err);
return;
}
Success && Success();
if (__self.__pool) {
delete this.pool;
delete this.__pool;
}
});
}
}
module.exports = MySqlHelper;