MySQL2 Package with Pooling

what we will learn here:

establishing connections

pool options

Install the package

npm install mysql2

Create a One-to-One connection

Start by creating a connection to the database.

Use the username and password from your MySQL database.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword"
});

Testing whether connection was successful or not?

con.connect((err) => {
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});

Making a query

con.query('SELECT * FROM authors', (err,rows) => {
  if(err) throw err;

  console.log('Data received from Db:');
  console.log(rows);
});

INSERT Query

const author = { name: 'Craig Buckler', city: 'Exmouth' };
con.query('INSERT INTO authors SET ?', author, (err, res) => {
  if(err) throw err;

  console.log('Last insert ID:', res.insertId);
});

UPDATE Query

con.query(
  'UPDATE authors SET city = ? Where ID = ?',
  ['Leipzig', 3],
  (err, result) => {
    if (err) throw err;

    console.log(`Changed ${result.changedRows} row(s)`);
  }
);

DELETE Query

con.query(
  'DELETE FROM authors WHERE id = ?', [5], (err, result) => {
    if (err) throw err;

    console.log(`Deleted ${result.affectedRows} row(s)`);
  }
);

How to show brought data into normal sentences?

rows.forEach( (row) => {
  console.log(`${row.name} lives in ${row.city}`);
});

Output:

Michaela Lehr lives in Berlin
Michael Wanyoike lives in Nairobi
James Hibbard lives in Munich
Karolina Gawron lives in Wrocław

Import it in Application

const mysql = require('mysql2');

Create a connection pool for the db

const mysql = mysql.createPool()

SEQUELIZE

MYSQL 2 vs SEQUELIZE

Featuremysql2Sequelize
Control over SQLFull controlLimited (high-level ORM)
PerformanceHigher (low-level driver)Slight overhead
Ease of UseManual SQL queriesEasier with models & queries
RelationshipsManual joins neededBuilt-in associations
TransactionsManual handlingBuilt-in
SuitabilitySimple apps, high controlComplex apps with relations