MySQL2 连接池

问题描述 投票:0回答:1

我正在尝试使用连接池连接到我的数据库。其余的 api 使用 Node 和 Express,我使用 mysql/promise 作为连接池,但是当我运行代码时出现错误

这是我的代码

import express from 'express';
import mysql2 from 'mysql2';
import multer from 'multer';
import path from 'path';
import dbPool from './db.js';
import dotenv from 'dotenv';
dotenv.config()

const route = express.Router();

route.get("/", (req, res) => {
    dbPool.query("SELECT * FROM vehicles", (err, result) => {
        if (err) {
            console.error("Loading Failure:", err);
            res.status(500).send("Loading Failure");
        } else {
            res.send(result);
        }
    });
})

这是我的连接池

import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

const dbPool = mysql.createPool({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    waitForConnections: true,
    connectionLimit: 20, // Adjust as per your requirements
    queueLimit: 0,

})

dbPool.getConnection((err, connect) => {
    if (err) {
        console.log(err)
    } else if (connect) {
        console.log("Pool Connected")
    }
    connect.release()
})


export default dbPool;

我希望获得有关车辆表中存储的车辆的信息,但我不断收到错误

Error: Callback function is not available with promise clients.
    at PromisePool.query (C:\Users\gwala\carRental\rental_api\node_modules\mysql2\promise.js:358:13)
    at file:///C:/Users/gwala/carRental/rental_api/routes/vehicles.js:12:12
    at Layer.handle [as handle_request] (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:346:12)  
    at next (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:280:10)
    at Function.handle (C:\Users\gwala\carRental\rental_api\node_modules\express\lib\router\index.js:175:3)
express connection-pooling node-mysql2
1个回答
0
投票

问题是您正在使用“mysql2/promise”,然后在

getConnection
中使用回调函数。

dbPool.getConnection((err, connect) => {
    if (err) {
        console.log(err)
    } else if (connect) {
        console.log("Pool Connected")
    }
    connect.release()
})

文档:https://sidorares.github.io/node-mysql2/docs显示您应该使用

const conn = await pool.getConnection();

// Do something with the connection
await conn.query(/* ... */);

// Don't forget to release the connection when finished!
pool.releaseConnection(conn);

由于您还要检查错误,我想一个简单的

trycatch
块应该可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.