Implementation of Node connection to MySQL query transaction processing

Implementation of Node connection to MySQL query transaction processing

I have used MySQL many times, and I mainly play with NodeJS. I wrote an article specifically to talk about how to connect nodejs to mysql database. Before use, please check whether your computer has the following environment!

  • The nodejs execution environment.
  • MySQL database environment (download address).
  • Navicat is a graphical operating software that connects to MySQL database. (optional)

Enter the topic mysql add, delete, modify and query

First, we download a dependency package called mysql. This package connects to the database through nodejs code to operate the database.

Create a folder and quickly generate the pakeage.json file

D:\nodejs_mysql>npm init -y # Quickly create package management files

Install Dependencies

D:\nodejs_mysql>npm i mysql -D # Install mysql dependency package

Create an index.js file with the following code

const mysql = require("mysql");

// Create a mysql connection pool const pool = mysql.createPool({
  host: "127.0.0.1", // The address 127.0.0.1 for connecting to the database is the local mysql
  user: "root", // Username for connecting to the database root has the highest authority password: "", // Password for connecting to the database database: "apm", // Database name for operation port: "3306", // Port number for connecting to MySQL multipleStatements: true, // This item can be ignored if you want to execute multiple SQL statements at once });

function select() {
  // Request to connect to mysql
  pool.getConnection((err, connection) => {
    // Report an error if the connection is not successful if (err) throw err;
    // Get a connection object and call the query method to execute the SQL statement let sql = "select * from goods";
    // Run the SQL statement query The second parameter is the parameter required by the SQL statement, you can leave it blank connection.query(sql, (errors, results, fields) => {
      // Release the connection connection.release();
      // If there is an error when running the sql statement, throw an error if (errors) throw errors;
      console.log(results);
      console.log(fields);
    });
  });
}

select();

The above code queries the data of a data table goods in the apm database. results are the data retrieved from the database.

Encapsulation method uses Promise to query the database

// index.js
// ... Ignore the previous code to create a MySQL connection pool function query(sql, params) {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      // Report an error if the connection is not successful if (err) return reject(err);
      // Get a connection object and call the query method to execute the SQL statement // Run the SQL statement query The second parameter is the parameter required by the SQL statement, which can be omitted connection.query(sql, params, (errors, results, fields) => {
        // Release the connection connection.release();
        // If there is an error in running the sql statement, throw an error if (errors) return reject(errors);
        resolve(results);
      });
    });
  });
}

query("select * from goods", null).then((result) => {
  console.log(result);
});
module.exports = {
  query,
};

use

// data.js
const index = require("./index.js");
var sql = "select * from goods";
index
  .query(sql, null)
  .then((result) => {
    // do anything ....
  })
  .catch((err) => {
    // error
    console.log(err);
  });

This exposes an interface for the database to run SQL. Use .then to chain calls through promise .

MySQL transaction processing

When it comes to MySQL transactions, I will not go into too much detail. Here is a link for your convenience. MySQL Transaction Processing

Let's get straight to the point and use promise to encapsulate MySQL事務處理.

// index.js

// .... Part of the code to create a pool /**
 * mysql transaction processing * @param {Array} sqls sql statement to be executed * @param {Array} params corresponding to the parameters of the above sql statement * @returns {Promise} returns a Promise
 */
function transaction(sqls, params) {
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, connection) {
      // Connection failed promise returns failure directly if (err) {
        return reject(err);
      }
      // If the statement and parameter number do not match, promise returns failure directly if (sqls.length !== params.length) {
        connection.release(); // Release return reject(new Error("The statement does not match the passed value"));
      }
      // Start executing transaction connection.beginTransaction((beginErr) => {
        // Failed to create transaction if (beginErr) {
          connection.release();
          return reject(beginErr);
        }
        console.log("Start executing transactions, a total of " + sqls.length + " statements");
        // Return a promise array let funcAry = sqls.map((sql, index) => {
          return new Promise((sqlResolve, sqlReject) => {
            const data = params[index];
            connection.query(sql, data, (sqlErr, result) => {
              if (sqlErr) {
                return sqlResolve(sqlErr);
              }
              sqlReject(result);
            });
          });
        });
        // Use the all method to check the status of each promise in it Promise.all(funcAry)
          .then((arrResult) => {
            // If each sql statement is executed successfully, it will come to this point. Here, the transaction needs to be committed, and the previous sql execution will take effect. // Commit the transaction connection.commit(function (commitErr, info) {
              if (commitErr) {
                // Transaction submission failed console.log("Transaction submission failed: " + commitErr);
                // Transaction rollback, previously executed SQL statements are invalid connection.rollback(function (err) {
                  if (err) console.log("Rollback failed: " + err);
                  connection.release();
                });
                // Return promise failure status return reject(commitErr);
              }

              connection.release();
              // The transaction successfully returns the result of each sql execution as an array structure resolve(arrResult);
            });
          })
          .catch((error) => {
            // If one of the multiple SQL statements reports an error during execution, rollback directly connection.rollback(function () {
              console.log("sql execution failed: " + error);
              connection.release();
              reject(error);
            });
          });
      });
    });
  });
}
module.exports = {
  transaction,
};

After that, you only need to call this method to execute the mysql transaction

// data.js
const index = require("./index.js");
var sqls = [
  "delete from goods where goods_id = ?", // delete statement "update goods set num = ? where goods_id = ?;", // update statement];
var params = [
  [1], // parmas is in array format and corresponds to the sql statement in sqls? [5, 3],
];

index
  .transaction(sqls, params)
  .then((arrResult) => {
    // do anything ....
  })
  .catch((err) => {
    // error
    console.log(err);
  });

This is the end of this article about the implementation of node connection mysql query transaction processing. For more relevant node connection mysql query transaction processing content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to implement distributed transactions in MySQL XA
  • MySQL database transaction example tutorial
  • Seven solutions for classic distributed transactions between MySQL and Golan
  • Analysis and summary of the impact of MySQL transactions on efficiency
  • MySQL transaction isolation level details
  • Detailed explanation of transactions and indexes in MySQL database
  • MySQL transaction analysis

<<:  Discussion on the browsing design method of web page content

>>:  Detailed explanation of MySQL database isolation level and MVCC

Recommend

Detailed explanation of querying JSON format fields in MySQL

During the work development process, a requiremen...

HTML meta viewport attribute description

What is a Viewport Mobile browsers place web page...

Summary of commonly used performance test scripts for VPS servers

Here is a common one-click performance test scrip...

How to set MySQL foreign keys for beginners

Table of contents The role of foreign keys mysql ...

How to configure MGR single master and multiple slaves in MySQL 8.0.15

1. Introduction MySQL Group Replication (MGR for ...

Detailed description of the life cycle of React components

Table of contents 1. What is the life cycle 2. Lo...

HTML discount price calculation implementation principle and script code

Copy code The code is as follows: <!DOCTYPE HT...

Detailed process of SpringBoot integrating Docker

Table of contents 1. Demo Project 1.1 Interface P...

Detailed code examples of seven methods for vertical centering with CSS

When we edit a layout, we usually use horizontal ...

How to lock a virtual console session on Linux

When you are working on a shared system, you prob...

Detailed tutorial on installing Docker and nvidia-docker on Ubuntu 16.04

Table of contents Docker Installation Nvidia-dock...

In-depth understanding of uid and gid in docker containers

By default, processes in the container run with r...

Record the steps of using mqtt server to realize instant communication in vue

MQTT Protocol MQTT (Message Queuing Telemetry Tra...