R
R
Roman2021-11-23 23:12:49
JavaScript
Roman, 2021-11-23 23:12:49

How to access database in another file?

Hello. I am learning js and node.js. There is a file with a database connection:

const mysql = require('mysql');

// Создаём подключение к БД
const connection = mysql.createPool({
    host: 'localhost', //Хост !
    user: 'root',       //Пользователь БД !
    database: 'server',   //Название БД !
    password: 'root',
    waitForConnections: true,
    connectionLimit: 10,    //Максимальное количество подключений **
    queueLimit: 0
});

//Делаем возможность подключения других файлов к БД
exports.connection = connection;


There is a second file where you need to connect to the same database.

//Инклюдим подключение к БД
const DB = require('../system/DB.js');


mp.events.add('playerJoin', (player) => {
    console.log(`[SERVER]: ${player.name} has joined the server!  ${player.rgscId}`);
    
    connection.query("SELECT * FROM accounts",     // ТУТ НАДО ПОДКЛЮЧИТЬСЯ К БАЗЕ
    function(err, results, fields) {
        console.log(err);
        console.log(results); // собственно данные
        console.log(fields); // мета-данные полей 
    });
    connection.end();
});

How to do it right? Mistake:
ReferenceError: connection is not defined

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex_mos, 2021-11-23
@yagyar001

DB.query...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question