node 连接数据的方式分为两种,一直为直连,一种使用来连接池,连接池的目的是更好的管理 mysql 数据库的连接,优化连接性能。
废话不多说了,上代码
const mysql = require("mysql2");
class PoolConnect {
constructor() {
this.pool = mysql.createPool({
host: "localhost",
user: "root",
password: "xxxxxx", //你的数据库密码
port: 3306, // 修正为数字
database: "testblog",
// 注意:authPlugins 可能不是必需的,取决于您的 MySQL 服务器配置
// 如果需要,请确保它与您的 MySQL 服务器配置相匹配
authPlugins: "caching_sha2_password",
});
// 这是一个连接监听的方法,通过此方法可以监听连接池状态等信息
this.pool.on("connection", (connection) => {
// 可以在此进行连接监听,比如 写日志等等
connection.query("SET SESSION auto_increment_increment=1", (error) => {
if (error) {
console.error("Error setting auto_increment_increment:", error);
}
});
});
}
//获取 pool
getPool() {
return this.pool;
}
//获取连接方法
getConnection(callback) {
this.pool.getConnection((err, connection) => {
if (err) {
return console.log("err:", err);
}
callback(connection);
});
}
}
module.exports = PoolConnect;
对 mysql 连接做了封装,建立了一个 连接池类,连接池类的构造函数中包含如下信息:
pool: ---- 建立的连接池
pool--connection: 监听器:用于连接池 日志监听等,如若不需要,可以移除
pool--- 建立的连接池
两个构造方法:
getPool --- 获取连接池
getConnection--连接池连接数据库方法,方便统一处理错误,同时方便直接调用连接方法进行数据库操作,其中入参为一个回调函数,回调函数中的默认参数为 connection,通过它 来进行数据库的增删改查操作。
如何使用呢:
// 引入连接池类
const PoolConnect = require('./poolConnect');
// 创建PoolConnect的实例
const pool= new PoolConnect();
// 直接从PoolConnect实例上调用getConnection方法
pool.getConnection(connection => {
// 使用连接执行查询
...
// 释放连接
connection.release();
});