Web-Connect to MySQL using NodeJS

introduce

        To access and store data easily, we should store and keep data easily accessible. This storage method should be efficient, fast and reliable. The reason we use a database is because it is faster to access than a file, especially as the amount of data increases. Additionally, it allows us to locate information without having to read the entire document. Given this unit's focus on SQL-based databases, we will delve into MySQL.

        The following sections will discuss how to install MySQL on NodeJS and use the MySQL module. Next, we'll dive into how to create, insert/update, and delete data in a MySQL database. If you are interested in PostgreSQL and MongoDB, check out the optional sections on these topics.

InstallMySQL

        MySQL is a relational database management system (RDBMS) developed by Oracle and based on Structured Query Language (SQL). In this section, we will see how to install MySQL on Windows platform.

        MySQL is only available on Microsoft Windows 64-bit operating systems. For information on supported Windows platforms, see https://www.mysql.com/support/supportedplatforms/database.html.

        There are different ways to install MySQL on Microsoft Windows. If you want to install MySQL in a Windows environment, using the MySQL installer is the easiest way. The MySQL installer provides you with an easy-to-use wizard to help you install MySQL and the following components:

  •         MySQL Server
  •         All available connectors
  •         MySQL Workbench with sample data model
  •         MySQL Notification Tool for Excel and Microsoft Visual Studio
  •         MySQL sample database
  •         MySQL Documentation

        To download the MySQL installer, please visit the following link http://dev.mysql.com/downloads/installer/.

        To install MySQL using the MySQL installer, double-click the MySQL installer file and follow the instructions.

        To install MySQL on MacOS, please refer to the following link: https://dev.mysql.com/doc/refman/5.7/en/macos-installation-pkg.html

        Video on installing MySQL on Windows: https://www.youtube.com/watch?v=OM4aZJW_Ojs

        Video of installing MySQL on MacOS: https://www.youtube.com/watch?v=-BDbOOY9jsc

Create database on MySQL

 A new SQL database         can be created using  the CREATE DATABASE statement.

CREATE DATABASE `testDB` ;

        After creating a database, you must explicitly select the database for use. You can make testDB the current database using the statement " use  testDB;"

USE testDB;

        CREATE TABLE  statement can be used to create a new table in the database.

CREATE TABLE Persons(
  id int(5),
  name varchar(50),
  suburb varchar(50),
  city varchar(50),
  PRIMARY KEY (id)
);

        New records can be inserted into the Persons table using the INSERT INTO command.

INSERT INTO Persons(id, name, city) VALUES
(1, 'John', 'Hawthorn', 'Melbourne'),
(2, 'Jane', 'Paramatta', 'Sydney')
(3, 'Tom', 'CBD', 'Brisbane');

Using the MySQL module on NodeJS

        This section demonstrates how to install the mysql module, a JavaScript client for MySQL. In this module, you will learn how to use the MySQL module to connect to a MySQL database and perform common CRUD operations. Before continuing, make sure you have access to the MySQL database.

        After accessing the MySQL database, open Powershell or Terminal and create a new folder.

mkdir databaseMysql

        Then, navigate to the newly created folder and create a new project using the following command, which will create a package.json file

npm init -y

        Then, install the mysql module.

npm install mysql2

        The following code imports the mysql module. Note that mysql and mysql2 are almost identical except that mysql2 is more API compatible, which will be useful in the following sections.

const mysql = require('mysql2');

        The following code creates a connection to the MySQL database. This script contains a connection variable along with the configuration of the MySQL database, which includes the host to connect to, port, user (username for mysql connections), password (for mysql connections), and database (the database node application we want to connect to ). The default Mysql database port in the system is 3306. This code is further demonstrated in the video below.

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'user',
  password: 'password',
  database: 'testDB'
});

        Then, we will establish a connection between the application and MySQL. Therefore, we must call the connect function on the connection variable we have defined above.

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected!');
});

        Once the connection is successfully established, a " Connected " message should appear in the console. If a failure occurs (for example, the wrong password is entered), a callback is triggered, which is passed an instance of the JavaScript Error object (err).

 

Read database

        In order to read data from the database, we must call a function called query and provide a SQL query as a parameter.

connection.query('SELECT * FROM Persons', (err,rows) => {
  if(err) throw err;
  console.log('Data received from Db:');
  console.log(rows);
  rows.forEach( (row) => {
    console.log(`${row.LastName} lives in ${row.City}`);
})
});

Create/insert data into database

        Call query() and send the corresponding SQL statement to insert the data as shown below.

const person = { PersonID: 220, LastName: 'Craig', FirstName: 'Buckler', Address: 'Burwood', city: 'London' };
connection.query('INSERT INTO Persons SET ?', person, (err, res) => {
  if(err) throw err;
  console.log('Last insert ID:', res.insertId);
});

renew

        To update the database table, we need to use the query() function and send the necessary SQL statements as shown below. The number of changed rows can   be obtained by using result.changedRows

connection.query(
  'UPDATE Persons SET City = ? Where PersonID = ?',
  ['Sydney', 221],
  (err, result) => {
    if (err) throw err;
    console.log(`Changed ${result.changedRows} row(s)`);
  }
);

delete

        To delete data from the database table, we need to use the query() function and send the necessary SQL statements as shown below.

connection.query(
  'DELETE FROM Persons WHERE PersonID = ?', [221], (err, result) => {
    if (err) throw err;

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

Guess you like

Origin blog.csdn.net/qq_54813250/article/details/133658115