nodejs mysql connection 1

nodejs mysql connection

//put these lines in a seperate file
const mysql = require('mysql2');

const connection = mysql.createPool({
    host: "localhost",
    user: "",
    password: "",
    database: ""
    // here you can set connection limits and so on

module.exports = connection;

//put these on destination page
const connection = require('../util/connection');

async function getAll() {
    const sql = "SELECT * FROM tableName";
    const [rows] = await connection.promise().query(sql);
    return rows;
exports.getAll = getAll;

Here is what the above code is Doing:
1. We’re creating a connection pool using the mysql2 package.
2. We’re exporting the connection pool so that we can use it in other files.
3. We’re importing the connection pool in the destination file.
4. We’re creating a function that uses the connection pool to query the database.
5. We’re exporting the function so that we can use it in other files.

Now, we can use the function in other files.

const db = require(‘../util/db’);

async function getAll() {
const rows = await db.getAll();
return rows;
exports.getAll = getAll;

Similar Posts