node连接Mysql

使用最新的 npm mysql 连接库 mysql2

1
npm install --save mysql2

基础使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const mysql = require("mysql2");

const connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "123456",
database: "practice",
});

connection.query("SELECT * FROM customers", function (err, results, fields) {
console.log(results);
console.log(fields.map((item) => item.name));
});

promise 版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const mysql = require("mysql2/promise");

(async function () {
const connection = await mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "guang",
database: "practice",
});

const [results, fields] = await connection.query("SELECT * FROM customers");

console.log(results);
console.log(fields.map((item) => item.name));
})();

连接池

需要操作数据库的时候,建立连接,用完之后释放连接。但这样性能并不高。因为数据库的连接建立还是很耗时的,而且一个连接也不够用。我们一般都是用连接池来管理

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
const mysql = require("mysql2/promise");

(async function () {
const pool = mysql.createPool({
host: "localhost",
user: "root",
password: "123456",
database: "practice",
// 是指如果现在没有可用连接了,那就等待,设置为 false 就是直接返回报错。
waitForConnections: true,
// 是指定最多有多少个连接,比如 10 个,那就是只能同时用 10个,再多需要排队等。
connectionLimit: 10,
// 是指定最多有多少个空闲的,超过这个数量的空闲连接会被释放
maxIdle: 10,
// 是指空闲的连接多久会断开
idleTimeout: 60000,
// 是可以排队的请求数量,超过这个数量就直接返回报错说没有连接了。设置为 0 就是排队没有上限。
queueLimit: 0,
// enableKeepAlive、keepAliveInitialDelay 是保持心跳用的,用默认的就好。
enableKeepAlive: true,
keepAliveInitialDelay: 0,
});

const [results] = await pool.query("select * from customers");
console.log(results);
})();

// 可以手动取
const connection = await pool.getConnection();
const [results] = await connection.query("select * from orders");
console.log(results);

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!