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
39
40
41
42
43
44
45
46
47
48
49
50
51
新建db.js, 内容如下:

const mysql = require('mysql');

// 创建连接池
const pool = mysql.createPool({
connectionLimit: 5,
host: process.env.dbHost,
user: process.env.dbUser,
password: process.env.dbPassword,
database: process.env.dbDatabase,
multipleStatements: true
});

let query = function (sql, values) {
// 返回一个 Promise
return new Promise((resolve, reject) => {
pool.getConnection(function (err, connection) {
if (err) {
reject(err)
} else {
connection.query(sql, values, (err, rows) => {
if (err) {
reject(err)
} else {
resolve(rows)
}
// 结束会话
connection.release()
})
}
})
})
}

module.exports = {
query
}
使用
const handler = require('./db.js')

handlder.query({
sql: 'select * from table where id = ?',
params: [id],
success: res => {
console.log(res);
},
error: err => {
console.log(err);
}
});