【问题标题】:mysql2/promise require database connection filemysql2/promise 需要数据库连接文件
【发布时间】:2021-06-09 11:50:57
【问题描述】:

在使用 Node.JS 之前,我只使用过 PHP。在使用 MYSQL 时,我能够在 PHP 中做的是,我可以将 database.php 文件包含在我想要执行查询的文件中。

在 Node.Js 中似乎不一样。这是我的 database.js 文件

const mysql  = require("mysql2/promise");

const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'XXXX',
    database: 'nodelogin'
});

module.exports = db;

然后我在我的文件 login.js 中需要这个

const db  = require("../../database");

但是,当我尝试运行 db.query(sql, [variable]) 时,我得到 db.query is not a function

这是为什么?它不应该那么复杂还是应该的?

【问题讨论】:

标签: mysql node.js express promise


【解决方案1】:

如果您改用connection pool,则可以将池包含一次,然后对其调用查询,如下所示:

db-config.js

const mysql = require("mysql2/promise");

console.log("Creating connection pool...")
const pool = mysql.createPool({
    host: 'localhost',
    user: 'user',
    database: 'test_db',
    password: 'password'
})

module.exports = pool;

test.js

// Require to whereever db-config is 
const pool = require('./db-config.js');

async function testQuery() {
    const results = await pool.query("select * from users");
    console.table(results[0]);
}

testQuery();

【讨论】:

  • 这样做,require 被缓存,但在多个地方,如内部快速处理程序会快速敲击连接,反模式
  • 但这意味着我必须在我所做的每个查询中都包含“database.js”?没有办法在每个文件中只包含一次吗?
  • 好点@LawrenceCherone,我已经更新了答案。
猜你喜欢
  • 2021-04-25
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 2015-12-03
  • 1970-01-01
  • 2017-07-05
  • 2012-04-26
相关资源
最近更新 更多