【问题标题】:Mysql getConnection() doesn't return the callback function in nodejsMysql getConnection() 不返回nodejs中的回调函数
【发布时间】:2019-09-08 06:13:30
【问题描述】:

我正在尝试从 nodejs 中的 mysql 连接池获取连接。但是池的 getConnection 方法不返回回调函数。 (所以它不会显示任何错误或返回连接)。但我的 mysql 工作台显示已建立连接。仍然当我使用连接时,它不会在回调中返回任何内容。

   var pool = mysql.createPool({
      connectionLimit: 10,
      host: "localhost",
      database: "database",
      user: "root",
      password: "password"
   });

   exports.query = function (query, params, callback) {
      pool.getConnection(function (err, connection) {
        if (err) {

            console.log(err);
            connection.release();
            callback(err.code, null);
        }
        console.log("connected");
        connection.query(query, params, function (err, results) {
            connection.release();
            if (!err) {
                callback(null, results);

            }
            else {

                callback(err.code, null);

            }

        });

        connection.on('error', function (err) {
            connection.release();
            callback(err.code, null);
        });

    });           

}

这是我使用数据库查询的地方。

 exports.getLevels= function(callback){
    var query = 'SELECT * FROM levels';
    db.query(query,null, function (err, results) {
       if (err) {
          console.log(err);
       }
       console.log('reached');
       callback(err, results);
    });
 }

【问题讨论】:

    标签: mysql node.js database


    【解决方案1】:

    试试这个可能会有帮助

    我正在使用这个 npm 包 mysql 使用这个命令

    npm i --save mysql
    

    我认为要么你有一个本地用户和远程用户,要么你的 mysql 实例没有运行。确保您已经创建了一个在 nodejs 脚本中访问的本地用户,您可以从 here 获取帮助并使用 this 检查连接。

    const MySQL_DB = require( "mysql" );
    let DB_Pool = MySQL_DB.createPool( {
        connectionLimit: 15,
        multipleStatements: true,
        host: "localhost",
        user: "root",
        password: "abcdefgh",
        database: "working_db",
        port: "3306"
    } );
    
    function GetDatabaseResponse( query ) {
    
        return new Promise( ( resolve, reject ) => {
            DB_Pool.getConnection( ( ConnectionErrorMessage, DB_LocalConnection ) => {
                if ( ConnectionErrorMessage ) {
                    console.log( "DataBase Connection Failed" );
                    console.log( ConnectionErrorMessage );
                    resolve( ConnectionErrorMessage );
                    return;
    
                } else {
    
                    DB_LocalConnection.query( query, ( ProcedureErrorMessage, ProcedureCallResult ) => {
                        DB_LocalConnection.release();
                        if ( ProcedureErrorMessage ) {
                            console.log( "DataBase Query Execution Failed" );
                            console.log( DB_ProcedureCall );
                            console.log( ProcedureErrorMessage );
                            resolve( ProcedureErrorMessage );
                            return;
    
                        } else {
                            resolve( ProcedureCallResult );
                            return;
                        }
                    } );
                }
            } );
        } );
    }
    
    ( async () => {
        let query = 'SELECT * FROM levels';
        let Result = await GetDatabaseResponse( query );
        console.log( Result );
    } )();
    

    这是您的代码实现,它在我这边运行良好。

    databaseFile.js

    const mysql = require( "mysql" );
    var pool = mysql.createPool({
        connectionLimit: 15,
        multipleStatements: true,
        host: "localhost",
        user: "root",
        password: "abcdefgh",
        database: "working_db",
        port: "3306"
     });
    
    module.exports =( query, callback) => { 
    
        pool.getConnection((err, connection) => {
          if (err) {
              console.log(err);
              connection.release();
              callback(err.code, null);
          }
          console.log("connected");
          connection.query(query,  (err, results) => {
              connection.release();
              if (!err) {
                  callback(null, results);
              }
              else {
                  callback(err.code, null);
              }
          });
    
          connection.on('error',(err) => {
              connection.release();
              callback(err.code, null);
    
          });
    
      });
    }
    

    index.js

    let GetBataBaseResponse = require("./databaseFile");
    
    GetBataBaseResponse("Select * from tblagents",(error, result) => {
        console.log("error",error);
        console.log("result",result);
    });
    

    如果你还有问题给我留言。

    【讨论】:

    • 似乎我无法将pool.getConnection 包装在一个函数中。当我在自己的函数之外运行它时,回调被返回。 (这意味着我在创建池后立即添加了pool.getConnection,只是为了看看会发生什么,它工作正常,但不是这样。
    • 我可以连接到 getResponse 方法所在的同一文件中的池。我也可以从另一个本地函数访问它(我可以从另一个本地函数调用 getResponse 方法。但是一旦我导出了它停止正确连接的功能。
    • 我已经更新了答案。当我使用错误的凭据时,它就崩溃了。但是这个具有正确凭据的实现工作正常。
    • 我试过这个。只要我像您一样直接查询数据库,它就可以工作。但是,如果我尝试在导出的函数中做同样的事情,回调不会返回。我更新了我的问题,以显示我在导出函数中使用数据库查询的位置。
    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 2012-07-30
    • 2019-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 2013-03-16
    相关资源
    最近更新 更多