If you want to operate a MySQL database through a programming language like JavaScript (Node.js), you need to connect the MySQL database with the language first.
Therefore in this tutorial, I will show you how you can make a connection between JavaScript (Node.js) and MySQL DB.
Node.js MySQL database connection
Here we will use the npm mysql2 package to make connection with MySQL database. Let’s see how you can use this package –
First, install this package with the help of the following command.
npm install --save mysql2
After that, import this package
import mysql from 'mysql2';
The mysql2 package has a method called createConnection() that is used to create a connection with the MySQL database.
import mysql from 'mysql2';
const connection = mysql.createConnection({
options
});
Database information
We have to put the database information inside the createConnection() method with the help of the Options.
Database name | my_test_db |
Host of the DB | localhost |
User of the DB | root |
Password of the DB | Enter your DB password |
import mysql from 'mysql2';
const connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'my_test_db'
});
Verify that the database is connected successfully
import mysql from 'mysql2';
const connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'my_test_db'
});
// Verify that the database is connected successfully
connection.connect((error) => {
if(error){
console.error(error);
return;
}
console.log('The database is successfully connected.');
})
PS c:\#project\node-js\learn-node-js> node index.js
The database is successfully connected.
MySQL2 also supports Promise API
import mysql from 'mysql2/promise';
try{
const connection = await mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'my_test_db'
});
}
catch(err){
console.log(`${err.name}: ${err.message}`);
}
Promise/Non-promise connections from the same pool
MySQL2 also exposes a .promise() function on Pools, so you can create a promise/non-promise connections from the same pool.
import mysql from 'mysql2';
// Non-promise connection
const connection = mysql.createPool({
host:'localhost',
user:'root',
password:'',
database:'my_test_db'
});
// Promise connection
const connectionPromise = connection.promise();
// Query with non promise
connection.query('SQL query...', (err, row, fields) => {
...
});
// Query with Promise connection
connectionPromise.query('SQL query...')
.then(([row,fields]) => {
...
})
.catch(err => {
...
})