javascript - Some problems with the mysql module, about connection pools
淡淡烟草味
淡淡烟草味 2017-05-19 10:08:39
0
1
569

Some doubts about the official sample code of npm package mysql:
First look at the first code:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});

connection.connect();

connection.query('SELECT 1 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[ 0].solution);
});

connection.end();
You can see that after querying, call connection.end() to disconnect;
Look at the second piece of code:
var mysql = require('mysql') ;
var pool = mysql.createPool(...);

pool.getConnection(function(err, connection) {
// Use the connection
connection.query('SELECT something FROM sometable', function (error, results, fields) {

// And done with the connection. 
connection.release();

// Handle error after the release. 
if (error) throw error;

// Don't use the connection here, it has been returned to the pool. 

});
});

Called after the query is completed: connection.release();

Question 1 If these two pieces of code:
The first paragraph does not call
connection.end();
The second paragraph does not call
connection.release();
will occur What are the consequences?
2. What is the difference between the two?
3. What is the difference between these two pieces of code? How to understand this connection pool?
Personal understanding: Can the connection pool be understood as a cache? After querying a certain piece of data, the second query for the same data is directly retrieved from the cache, that is, from the pool;

淡淡烟草味
淡淡烟草味

reply all(1)
phpcn_u1582

1. Operations on the database must be synchronously blocked, because multiple connections are never allowed to operate a record at the same time. If you want to operate the database, you must first establish a connection, and the database does not allow unlimited establishment. Multiple connections, if a connection operation is completed and the connection is not disconnected or released, it will affect the establishment and use of subsequent connections, which needs to be avoided in high concurrency situations.
2. The functions of connection.end() and connection.release() are to release the current connection, but the objects are different. The former is for ordinary connections, while the latter is for connection pools.
3. The connection pool does have a cache function, but what it caches is not the specific data taken out by a certain operation, but the cached connection itself. In this way, the next time you operate the database, you no longer need to constantly establish and destroy connections. .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template