Home Web Front-end JS Tutorial Using MySQL connection pool with Node.js

Using MySQL connection pool with Node.js

Jun 06, 2018 am 11:20 AM
mysql connection pool node.js

This article mainly introduces the method of Node.js using MySQL connection pool, and analyzes the related module installation, connection, query and other usage skills of nodejs operating mysql connection pool based on specific examples. Friends who need it can refer to it

The example in this article describes how Node.js uses the MySQL connection pool. Share it with everyone for your reference, the details are as follows:

How to use MySQL in Nodejs

To connect Nodejs to MySQL, you can use the MysQL driver of Nodejs. accomplish. For example, we use "node-mysql" to connect to the database here. We use the following method to connect to the database:

First, we need to use the nodejs package management tool (npm) to install the mysql driver. The command line is as follows:

npm install musql
Copy after login

Now, to use mysql in a js file, add the following code to your file:

var mysql = require('mysql');
Copy after login

Next, we can use this module to connect to MySQL database. Of course, to connect to the database, you need to specify the host name, user name and password of MySQL Server. There are many other options that can be set, such as the database time zone, socketPath, and local address.

var connection = mysql.createConnection({
  host : "hostName",
  user : "username",
  password: "password"
});
Copy after login

Then, the following code will establish a new connection for you.

connection.connect();
Copy after login

Using this connection object, we can query the database as follows. We can use the connection.escape() method to prevent sql injection.

connection.query("use database1");
 var strQuery = "select * from table1";
 connection.query( strQuery, function(err, rows){
  if(err) {
   throw err;
  }else{
   console.log( rows );
  }
});
Copy after login

Finally, we can close the connection in two ways. Use connection.end or connection.destroy.

The following expression will ensure that all queries in the queue will be executed before the database connection is closed. Note that there is a callback function here.

connection.end(function(err){
// Do something after the connection is gracefully terminated.
});
Copy after login

The following expression will immediately close the database connection. And there are no callback functions or any events triggered.

connection.destroy( );
Copy after login

Nodejs uses MysQL connection pool

##Using the connection pool can help us better manage database connections. The database connection pool can limit the maximum number of connections, reuse existing connections, etc.

First, we need to create a connection pool:

var mysql = require('mysql');
var pool = mysql.createPool({
 host : "hostName",
 user : "username",
 password: "password"
});
Copy after login

Secondly, we can get a connection we need from the created connection pool:

pool.getConnection(function(err, connection){
});
Copy after login

Use the callback function Parameter connection to query the database. Finally, use the

connection.realease() method to release the database connection.

pool.getConnection(function(err, connection){
 connection.query( "select * from table1", function(err, rows){
  if(err) {
   throw err;
  }else{
   console.log( rows );
  }
 });
 connection.release();
});
Copy after login

Execute multiple query statements

For security reasons, multiple query statements are not allowed to be executed by default. To use the function of multiple query statements, you need to turn on this function when creating a database connection:

var connection = mysql.createConnection( { multipleStatements: true } );
Copy after login

After this function is turned on, you can use multiple query statements at the same time like the following example:

connection.query('select column1; select column2; select column3;', function(err, result){
 if(err){
  throw err;
 }else{
  console.log(result[0]);  // Column1 as a result
  console.log(result[1]);  // Column2 as a result
  console.log(result[2]);  // Column3 as a result
 }
});
Copy after login

Use of mysql connection pool in node.js

If you don’t want the program to get stuck or wait too long when querying data, generally It is not recommended to use this link for all queries after opening a connection in node and not close it, because you will know why after you try it

Node.js mysql connection pool module

1. Installation node's mysql module

npm -install -g node-mysql
Copy after login

2. Create a class library, let's call it mysql.js, and then the content is as follows:

var mysql=require("mysql");
var pool = mysql.createPool({
 host: 'localhost',
 user: 'user',
 password: 'password',
 database: 'database',
 port: port
});
var query=function(sql,callback){
 pool.getConnection(function(err,conn){
  if(err){
   callback(err,null,null);
  }else{
   conn.query(sql,function(qerr,vals,fields){
    //释放连接
    conn.release();
    //事件驱动回调
    callback(qerr,vals,fields);
   });
  }
 });
};
module.exports=query;
Copy after login

3. Use the following in the js class

var query=require("./lib/mysql.js");
query("select 1 from 1",function(err,vals,fields){
 //do something
});
Copy after login
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Configuration method without dev-server.js in vue2.0

Use Vue in Vue. set method to dynamically add object attributes

How to dynamically bind attributes of form elements in vue

The above is the detailed content of Using MySQL connection pool with Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

How does Node.js do GC (garbage collection)? The following article will take you through it.

What should I do if node cannot use npm command? What should I do if node cannot use npm command? Feb 08, 2023 am 10:09 AM

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

See all articles