使用最新的 npm mysql 连接库 mysql2
基础使用
| 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 版本
| 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", waitForConnections: true, connectionLimit: 10, maxIdle: 10, idleTimeout: 60000, queueLimit: 0, 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);
|