Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
MySQL is an open-source traditional database based on a relational database management system. Unlike NoSQL databases, MySQL stores the data with the help of tables, rows, and columns.
There are following steps to connect MySQL with Node JS:
mkdir mysql-with-node-app. Then, We will open the folder mysql-with-node-app in the Visual Studio Code using the following commands:cd mysql-with-node-app
code .npm init -y. The command npm init -y will craete a file package.json inside the folder mysql-with-node-app.mysql with the following command:npm install mysql --savemysql -u root -p
Enter password: **********library-db using the command:CREATE DATABASE library_db;library_db is created with the command:mysql> SHOW DATABASES;+--------------------+
| Database |
+--------------------+
| library_db |
| sys |
| world |
+--------------------+server.js and require the mysql module in the server.js file as show below:const mysql = require('mysql')createConnection() method. The createConnection() method accepts the database credentials (i.e. host, user, password, etc).const initMysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'library_db',
})connect() method.// Connect myS:QL with node app
> initMysqlConnection.connect((error) => {
if (error) {
console.log(error)
}
console.log('Connected to the MySQL database')
})node server.js and get the following output:Connected to the MySQL databaseend() method. The end method allows the execution of queries that are already in the queue before ending the connection.connectMysql.end((err) => {
if (err) {
console.log(error)
}
console.log('Connection closed')
})destroy() method. The destroy method ends the connection immediately as well as all events and callback triggered during the connection.connectMysql.destroy()createTable.js inside the folder mysql-with-node-app. Then, we will write an SQL string to create a table in the MySQL database:// Creating table in mySQL database
const books = `CREATE TABLE IF NOT EXISTS books
(id INT PRIMARY KEY AUTO_INCREMENT,
book_title VARCHAR(255) NOT NULL)`books using query() method that will create a table named books in the database library_db:// Execute SQL string `books`
initMysqlConnection.query(books, (error, results, fields) => {
if (error) {
console.log(error)
}
console.log('Successfully created the table')
})
// Close the connection
initMysqlConnection.end()node createTable.js and verify whether the table books is created using the SQL commands:mysql> USE library_db;
mysql> SHOW TABLES;SHOW TABLES will display the following output:+----------------------+
| Tables_in_library_db |
+----------------------+
| books |
+----------------------+There are the following methods to insert a row in MySQL Table:
We will use the INSERT INTO statement to insert a row in the table books. Let's create a file insertRow.js inside the folder mysql-with-node-app.
Now, we will add the following code block to the file insertRow.js:
const mysql = require('mysql')
const initMysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'library_db',
})
// SQL string to insert a row in the table `books`
const insertStatement = `INSERT INTO books
(book_title)
VALUES
("Learn MySQL")`
// Execute SQL string `insertStatement`
initMysqlConnection.query(insertStatement)
// Close the connection
initMysqlConnection.end()node insertRow.js.Again, We will use INSERT INTO statement to insert multiple rows the table books. Let's create a file insertMultipleRows.js inside the folder mysql-with-node-app.
Now, we will add the following code block to the file insertMultipleRows.js:
const mysql = require('mysql')
const initMysqlConnection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Root@12345',
database: 'library_db',
})
// SQL string to insert rows in the table `books`
const insertStatement = `INSERT INTO books
(book_title)
VALUES ? `
const books = [['Learn Node JS'], ['Learn JavaScript']]
// Execute SQL string `insertStatement`
initMysqlConnection.query(
insertStatement,
[books],
(error, results, fields) => {
if (error) {
console.log(error)
}
console.log(`Successfully inserted ${results.affectedRows} rows`)
},
)
// Close the connection
initMysqlConnection.end()? as values with INSERT INTO statement. When we execute insertStatement using query() method, an array of arrays named books will replace the unnamed parameter ?.node insertMultipleRows.js to insert rows.// Execute SQL string `insertStatement`
initMysqlConnection.query(
insertStatement,
[books],
(error, results, fields) => {
if (error) {
console.log(error)
}
console.log(`Successfully inserted ${results.affectedRows} rows`)
},
)
// Close the connection
initMysqlConnection.end()mysql Node JS driver to connect MySQL with Node JS.mysql Node JS driver using the command npm install mysql.createConnection() method helps to configure the MySQL database with Node JS.connect() method to connect MySQL with Node JS.end() method to close the connection smoothly and .destroy() method to close the connection forcefully..query() method helps to execute MySQL statements and MySQL Queries.