node-mysql的使用

okgoes 2023-05-09 13:07:15
Categories: Tags:

编写mysql的config配置

1
2
3
4
5
6
7
8
9
{
    connectionLimit: 2,//连接数限制
    host: 'localhost',//数据库host
    user: 'root',//用户名
    password: 'root',//密码
    database: 'db',//数据库
    debug: false,//是否开启调试
    multipleStatements: true//是否允许同时执行多条语句
}

使用连接池创建一个mysql连接的单例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const mysql = require('mysql');
let conn = undefined;
/**
 * 数据库连接
 */
class Connection {
    /**
     * 构造函数
     * @param {Objectconfig
     */
    constructor(config) {
        this.config = config;
    }
    
    /**
     * 获取连接池
     * @return {Promise}
     */
    getPools() {
        let pool = mysql.createPool({
            connectionLimitthis.config.connectionLimit,
            hostthis.config.host,
            userthis.config.user,
            passwordthis.config.password,
            databasethis.config.database,
            debugthis.config.debug,
            multipleStatementsthis.config.multipleStatements
        });
        return pool;
    }
}
//此处暴露出一个连接池单例
module.exports = function(config) {
    if (!conn) {
        conn = new Connection(config).getPools();
    }
    return conn;
};

note:连接池不能使用事务,所以如果需要使用事务,需要通过连接池取得一个连接,通过这个连接使用事务,事务开始到结束必须使用同一个连接。

使用连接池获取连接

1
2
3
4
5
6
7
8
9
//Promise写法
return new Promise((resolve, reject)=>{
    pool.getConnection((err, conn)=>{
        if (err) {
            return reject(err);
        }
        resolve(conn);
    });
});