What is the method of node+mysql database connection pool connection?
Mysql has two connection methods: one is direct connection and the other is pooled connection. We are talking about pooled connection in this article.
In order to clear up the confusion, I will briefly write the code for direct connection, as follows:
var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'ac', password : '123456', database : 'textPro' }); connection.connect(); connection.query('SELECT * from1 userInfo', function (error, results, fields) { if (error) throw error; console.log('The solution is: ', results); }); connection.end();
The difference between createConnection and createPool is: createPool (connection pool) connection can be more reasonable Utilize server data to reduce data waste
After installation, start writing in db/index.js:
const mysql = require("mysql") //创建连接池 const db= mysql.createPool({ host : 'localhost', //连接主机 port : 3306, //端口号 database : 'test', //连接的是哪一个库 user : 'root', //用户名 password : '', //密码 connectionLimit : 50, //用于指定连接池中最大的链接数,默认属性值为10. //用于指定允许挂起的最大连接数,如果挂起的连接数超过该数值,就会立即抛出一个错误, //默认属性值为0.代表不允许被挂起的最大连接数。 queueLimit:3 })
After establishing the connection pool, you can directly use the connection pool objectgetConnection methodGet a connection from the connection pool. If there is no available connection in the connection pool, a database connection will be established implicitly.
const mysql = require("mysql") //创建连接池 const db= mysql.createPool({ host : 'localhost', //连接主机 port : 3306, //端口号 database : 'test', //连接的是哪一个库 user : 'root', //用户名 password : '', //密码 connectionLimit : 50, //用于指定连接池中最大的链接数,默认属性值为10. //用于指定允许挂起的最大连接数,如果挂起的连接数超过该数值,就会立即抛出一个错误, //默认属性值为0.代表不允许被挂起的最大连接数。 queueLimit:3 }) module.exports.query = (sql, values.callback) => { //err: 该参数是指操作失败时的错误对象。 //connection: 该值为一个对象,代表获取到的连接对象。当连接失败时,该值为undefined。 db.getConnection(function(err, connection) { if (err) { console.log('与mysql数据库建立连接失败'); pool.releaseConnection(); //释放链接 } else { console.log('与mysql数据库建立连接成功'); connection.query(sql,values,(err, res) => { if (err) { console.log('执行sql语句失败,查询数据失败'); //connection.release() 当一个连接不需要使用时,使用该方法将其归还到连接池中 release释放 connection.release(); callback(err,null) } else { console.log('执行sql语句成功'); callback(null,res) //pool.end() 当一个连接池不需要使用时,可以使用该方法关闭连接池 pool.end(); } }) } }) }
Introducing the calling db module
const query=require('./db').query; let sql='SELECT * FROM class WHERE class_id=? AND class_name=?' let userId=1; let userName='阿辰'; query(sql,[userId,userName],(err,res)=>{ if(err){ console.log('发生了错误***',err) return } console.log('找到了',res) })
The difference between const query=require('./db').query and const query=require('./db')
The first way of writing only obtains the query function in the "./db" module. If you need to use other export items, you need to obtain it again.
The second writing method obtains all the items exported by the "./db" module, and there is no need to repeatedly obtain different exported items in the code.
The above is the detailed content of What is the method of node+mysql database connection pool connection?. For more information, please follow other related articles on the PHP Chinese website!

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

The main reasons for slow MySQL query include missing or improper use of indexes, query complexity, excessive data volume and insufficient hardware resources. Optimization suggestions include: 1. Create appropriate indexes; 2. Optimize query statements; 3. Use table partitioning technology; 4. Appropriately upgrade hardware.

MySQL view is a virtual table based on SQL query results and does not store data. 1) Views simplify complex queries, 2) Enhance data security, and 3) Maintain data consistency. Views are stored queries in databases that can be used like tables, but data is generated dynamically.

MySQLdiffersfromotherSQLdialectsinsyntaxforLIMIT,auto-increment,stringcomparison,subqueries,andperformanceanalysis.1)MySQLusesLIMIT,whileSQLServerusesTOPandOracleusesROWNUM.2)MySQL'sAUTO_INCREMENTcontrastswithPostgreSQL'sSERIALandOracle'ssequenceandt

MySQL partitioning improves performance and simplifies maintenance. 1) Divide large tables into small pieces by specific criteria (such as date ranges), 2) physically divide data into independent files, 3) MySQL can focus on related partitions when querying, 4) Query optimizer can skip unrelated partitions, 5) Choosing the right partition strategy and maintaining it regularly is key.

How to grant and revoke permissions in MySQL? 1. Use the GRANT statement to grant permissions, such as GRANTALLPRIVILEGESONdatabase_name.TO'username'@'host'; 2. Use the REVOKE statement to revoke permissions, such as REVOKEALLPRIVILEGESONdatabase_name.FROM'username'@'host' to ensure timely communication of permission changes.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Zend Studio 13.0.1
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!
