在 nuxt3 中连贯 mysql
因为我的项目须要,依据前端的参数来连贯不同的数据库获取数据,我自身是个前端,奈何没有人给我写接口,刚好最近也在看 nuxt3 的货色,就用 nuxt3 一把梭了。公司外部自用小我的项目,有问题缓缓改,顺便学习一下。
装置
- 装置 mysql2
pnpm i mysql2
代码
简略封装一下,依据 type 获取数据库连贯字符串,创立连接池,用 map 缓存一下
import mysql from "mysql2/promise";// 缓存连接池const poolMap = new Map<string, mysql.Pool>();export async function useMysql(type: string): Promise<mysql.Pool | undefined> { // 获取数据库连贯字符串 const uri = getServerMysqlUri(type); // 从缓存中获取连接池 if (poolMap.has(type)) { const pool = poolMap.get(type); return pool; } try { const pool = await mysql.createPool(uri); // 缓存 poolMap.set(type, pool); return pool; } catch (error) { console.error("[Error]: mysql connection error."); return; }}
看了一下网上他人写的,发现他们有本人封装一下 query 原始查问的办法,我也仿写了一个
大抵就是最了一些谬误拦挡,查问完结之后开释了连贯
function query(pool: mysql.Pool, sql: string) { return new Promise(async (resolve, reject) => { try { // 获取连贯 const conn = await pool.getConnection(); // 查问 await conn .query(sql) .then((result) => { resolve(result); // 开释连贯 conn.release(); }) .catch((err) => { reject(err); }); } catch (error) { reject(error); } });}
我也不晓得 mysql2 具体怎么做的,需不需要开释连贯,大略看了一下网上他人写的
监听了一下申请的事件,发现开释后的conn.threadId是同一个,不开释时conn.threadId不一样,大略是开释之后可能复用吧
db.on("acquire", function (connection) { console.log("Connection %d acquired", connection.threadId);});db.on("release", function (connection) { console.log("Connection %d released", connection.threadId);});// 在query办法里获取连贯之后打印一下const conn = await db.getConnection();console.log("Connection %d connection", conn.threadId);
- 后果如图