“This article is participating in the technical topic essay node.js advanced road, click to see details”

preface

When connecting to the mysql database in Node, we need to use the third-party package mysql because Node has no method to connect to the mysql database.

yarn add mysql
Copy the code

Introduce the mysql third-party package

const mysql = require('mysql')
Copy the code

After introduction, there are two methods to connect to the database, createConnection and createPool.

CreateConnection Connects to the database

const db = mysql.createConnection({
  host: '127.0.0.1'.// localhost also works
  port: 3306.user: 'root'.password: '123456'.database: 'db'
})

// Connect to the database
db.connect((err) = > {
  if(err) return
  console.log('Connection Success')})// TODO:Data query
db.query('the SQL statement'.(err, res) = > {
  if(err) return console.log(err.message)
  console.log(res)
})


// Disconnect the database
db.end((err) = > {
  if(err) return
  console.log('Connection Closed')})Copy the code

This is an example of using createConnection to connect to a database.

CreatePool Creates a connection pool to connect to the database

We know that suggesting a connection pool is expensive and wasteful of performance. If we were to establish one or more connections for every client request, it would be a waste of resources on the server side.

So a connection pool needs to be created and maintained for multiple database connections in a server application, so that connections can be cached in the pool when they are not needed and removed from the pool when the next client request is received without having to re-establish a connection.

Complete sample

const db = mysql.createPool({
  host: '127.0.0.1'.// localhost also works
  port: 3306.user: 'root'.password: '123456'.database: 'db'
})

// Create a database connection. If no connection is available, implicitly create a database connection
db.getConnection((err, connection) = > {
  if(err){
    console.log('Connection failed')}else {
		console.log('Connection successful')
    db.query('the SQL statement'.(err, res) = > {
      if(err) return console.log(err.message)
      console.log(res)
      
      // Return to the connection pool when no longer in use
      connection.release()
      // Remove from connection pool when no longer in use
      connection.destory()
    })
  }
  
  // Disable the connection pool when it is no longer needed
  db.end()
})
Copy the code

conclusion

This is the difference between createConnection and createPool.

Refer to the article: www.cnblogs.com/xsilence/p/…