简体   繁体   中英

mysql2/promise require database connection file

I have only been working with PHP before going to Node.JS. What I was able to do in PHP when working with MYSQL was that I could include the database.php file in the files I wanted to execure queries in.

It doesn't seem to be the same in Node.Js. This is my database.js file

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

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

module.exports = db;

Then I require this in my file login.js

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

However, when I then try to run db.query(sql, [variable]) I get db.query is not a function .

Why is this? It shouldn't be that more complicated or should it?

If you use aconnection pool instead, you can include the pool once, then call query on it, like so:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM