【问题标题】:nodejs- TypeError: connection.connect is not a functionnodejs- TypeError:connection.connect 不是函数
【发布时间】:2018-01-25 14:05:47
【问题描述】:

我有一个使用 ExpressJS (Express 4) 框架开发的应用程序。我打算使用连接池而不是单个连接,听说它允许我们重用现有的数据库连接,而不是为 Node 应用程序的每个请求打开一个新连接。

所以在现有代码中,我进行了更改。 在以下代码中将mysql.createConnection 替换为mysql.createPool 注意:这只是建立数据库连接的应用程序的一部分。

  var mysql = require('mysql'),
    connection = mysql.createPool({
      host: 'localhost',
      user: 'root',
      password: '',
      database: 'test_db',
      port: 3306
    });
  connection.connect(function (err) {
    if (err) {
      console.log(err);
    }
  });

但是当我运行应用程序时,出现以下错误。

TypeError: connection.connect is not a function

谁能告诉我如何解决这个错误?谢谢!

Package.json 文件

{
  "name": "testapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "hola"
  },
  "author": "user",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "cake-hash": "0.0.6",
    "compression": "^1.7.1",
    "cors": "^2.8.4",
    "express": "^4.16.2",
    "https": "^1.0.0",
    "moment": "^2.19.2",
    "morgan": "^1.9.0",
    "mysql": "^2.15.0"
  }
}

【问题讨论】:

    标签: mysql node.js


    【解决方案1】:

    看起来你想要 .getConnection() 而不是 .connect() 的池。

    来自 mysql 包文档:

    var mysql = require('mysql');
    var pool  = mysql.createPool({
      host     : 'example.org',
      user     : 'bob',
      password : 'secret',
      database : 'my_db'
    });
    
    pool.getConnection(function(err, connection) {
      // connected! (unless `err` is set)
    });
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2020-07-12
      • 2020-07-14
      • 2017-11-22
      • 2021-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-13
      相关资源
      最近更新 更多