Nodejs application MySQL (purely translation)

Source: Internet
Author: User
Tags call back connection pooling emit type casting unix domain socket



Click here for the original


Directory
  • Install
  • Introduction
  • Contributors
  • Sponsors
  • Community
  • Establishing connections
  • Connection Options
  • SSL Options
  • Terminating connections
  • Pooling connections
  • Pool Options
  • Pool Events
  • Closing all the connections in a pool
  • Poolcluster
  • Poolcluster Options
  • Switching users and altering connection state
  • Server Disconnects
  • Performing queries
  • Escaping query values
  • Escaping query identifiers
  • Preparing Queries
  • Custom format
  • Getting the ID of an inserted row
  • Getting the number of affected rows
  • Getting the number of changed rows
  • Getting the connection ID
  • Executing queries in parallel
  • Streaming query rows
  • Piping results with STREAMS2
  • Multiple statement queries
  • Stored procedures
  • Joins with overlapping column names
  • Transactions
  • Timeouts
  • Error Handling
  • Exception Safety
  • Type Casting
  • Connection Flags
  • Debugging and reporting problems
  • Contributing
  • Running Tests
  • Todo
Install

$ npm Install MySQL
Introduction


Nodejs Drive MySQL. ①js write ② don't need to compile ③100%mit license



A simple example is given below:



 
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(err, rows, fields) { if (err) throw err;

  console.log(‘The solution is: ‘, rows[0].solution);
});

connection.end();


From the pest above, you can learn the following 2 points:


    • When you generate the same connection, the calling method is queued and executed sequentially.
    • End() to close the connection,the advantage of using this method is that all the remaining query statements in the queue are executed before sending a terminating semaphore to the MySQL server.
Establishing connections


The official recommendation is to create a link in this way (connection):



 
var mysql      = require(‘mysql‘); var connection = mysql.createConnection({
  host     : ‘example.org‘,
  user     : ‘bob‘,
  password : ‘secret‘ });

connection.connect(function(err) { if (err) {
    console.error(‘error connecting: ‘ + err.stack); return;
  }

  console.log(‘connected as id ‘ + connection.threadId);
});


Of course, creating a connection is actually hidden in a query statement:



 
var mysql      = require(‘mysql‘); var connection = mysql.createConnection(...);

connection.query(‘SELECT 1‘, function(err, rows) { // connected! (unless `err` is set) });


The above 2 methods are good, you can choose one to handle the error. Any error on the link (handshake or network) is considered a fatal error. More about error handling.


Connection Options


To create a link, you can configure the following options:


  • host: the hostname of the database you is connecting to. (Default:localhost)
  • port: The port number to connect to. (Default:3306)
  • localAddress: The source IP address to use for TCP connection. (Optional)
  • socketPath: The path to a UNIX domain socket to connect to. When used and ishostportignored.
  • user: The MySQL user to authenticate as.
  • password: The password of that MySQL user.
  • database: Name of the database to connection (Optional).
  • charset: The charset for the connection. This is called "collation" in the sql-level of MySQL (likeutf8_general_ci). If a sql-level charset is specified and then theutf8mb4default collation for that CharSet is used. (Default:‘UTF8_GENERAL_CI‘)
  • timezone: The timezone used to store local dates. (Default:‘local‘)
  • connectTimeout: The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default:10000)
  • stringifyObjects: Stringify objects instead of converting to values. See issue #501. (Default:false)
  • insecureAuth: Allow connecting to MySQL instances this ask for the old (insecure) authentication method. (Default:false)
  • typeCast: Determines if column values should is converted to native JavaScript types. (Default:true)
  • queryFormat: A custom query Format function. See Custom format.
  • supportBigNumbers: When dealing with big numbers (BIGINT and DECIMAL columns) in the database, you should enable this option (Default:).
  • bignumberstrings: Enabling both supportbignumbers and Bignumberstrings forces Big Numbers (BIGINT and DECIMAL columns) to being always returned as JavaScript String ob Jects (default: false). enabling supportbignumbers but leaving bignumberstrings disabled Would return big numbers as String objects only if they cannot be accurately represented With javascript number Obje cts  (which happens when they exceed the [ -2^53, +2^53] range), otherwise they would be returned as number objects. This option is ignored if supportbignumbers is disabled.
  • dateStrings: Force date types (TIMESTAMP, DATETIME, date) to being returned as strings rather then inflated into JavaScript date objects . Can istrue/falseor an array of type names to keep as strings. (Default:false)
  • debug: Prints protocol details to stdout. Can istrue/falseor an array of packet type names this should be printed. (Default:false)
  • trace: Generates stack traces on toErrorinclude the call site of the library entrance ("Long stack Traces"). Slight performance penalty for most calls. (Default:true)
  • multipleStatements: Allow multiple MySQL statements per query. Be careful with this, it could increase the scope of SQL injection attacks. (Default:false)
  • flags: List of connection flags to use other than the default ones. It is also possible to blacklist default ones. For more information, check Connection Flags.
  • ssl: Object with SSL parameters or a string containing name of the SSL profile. See SSL options.


In addition, you can choose a URL in addition to passing an object as a vector of options:


 
var connection = mysql.createConnection({
  host : ‘localhost‘,
  ssl  : { // DO NOT DO THIS // set up your ca correctly to trust the connection rejectUnauthorized: false }
});




Note: The value of query in the URL should first be tried to parse into JSON, if the parse fails, can only be considered a normal text string.


SSL Options


The Configure SSL option can be a string or an object. If it is a string, he will use a pre-defined SSL file configuration, which includes the following profiles:


    • "Amazon RDS": This profile was for connecting to a Amazon RDS server and contains the certificates from https://rds.amazonaws.com/doc/ Rds-ssl-ca-cert.pem and Https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem


If you want to link to another server, you need to pass object as options. The format type is the same as crypto.createcredentials. It is important to note that the parameter certificate contents of the string, not the name of the certificate:



var connection = mysql.createconnection ({host: ' localhost ', SSL: {Ca:fs.readFileSync (__dir Name + '/MYSQL-CA.CRT ')});






Of course you can also connect to a MySQL server so you don't need to provide the right CA. But you can't handle it like this:



 
var connection = mysql.createConnection({
  host : ‘localhost‘,
  ssl  : { // DO NOT DO THIS // set up your ca correctly to trust the connection rejectUnauthorized: false }
});
Terminating connections


There are 2 ways to terminate the link, but the adoptionend()is more elegant:






connection.end (function(err) { // The connection is terminated now}) ;






It will ensure that all queries that are already in the queue will continue to execute, and then send the Com_quit package to the MySQL server. If a fatal error (handshake or network) occurs before the Com_quit packet is sent, an err parameter is passed to the supplied callback. However, connection will be interrupted as usual, regardless of any errors.






The other is destroy (). It actually interrupts the underlying socket.



Connection.destroy ();






Andend()the difference is, destroy () will not have a callback, of course, will not produce the err as a parameter.





Pooling connections


Instead of a single management connection, create a connection pool,mysql.createPool(config):Read more about connection pooling.



 
var mysql = require(‘mysql‘); var pool  = mysql.createPool({
  connectionLimit : 10,
  host            : ‘example.org‘,
  user            : ‘bob‘,
  password        : ‘secret‘,
  database        : ‘my_db‘ });

pool.query(‘SELECT 1 + 1 AS solution‘, function(err, rows, fields) { if (err) throw err;

  console.log(‘The solution is: ‘, rows[0].solution);
});



Pooling allows us to better manipulate individual conenction or manage multiple connections:



 
var mysql = require(‘mysql‘); var pool  = mysql.createPool({
  host     : ‘example.org‘,
  user     : ‘bob‘,
  password : ‘secret‘,
  database : ‘my_db‘ });

pool.getConnection(function(err, connection) { // connected! (unless `err` is set) });


When you're done, you just need to call Connection.release (), and the connection will return to the pool and wait for someone else to use it:


var mysql = require(‘mysql‘); var pool  = mysql.createPool(...);

pool.getConnection(function(err, connection) { // Use the connection connection.query( ‘SELECT something FROM sometable‘, function(err, rows) { // And done with the connection.  connection.release(); // Don‘t use the connection here, it has been returned to the pool.  });
});


If you just want to close the connection and remove the pool, use Connection.destroy (). The pool will regenerate a new conenction waiting for the next use.






We know that pooling is lazy loading. If you configure your pool limit is 100 connection, but only need to use 5 at the same time, the pool will generate 5, will not generate more connection, in addition, connection is the way of Round-robin loop, from the top out, Return to the bottom of the.



When a previous connection is retrieved from the pool, a ping packet is sent to the server to determine if the link is good.





Pool Options


and options as a connection. Roughly the same, if you just create a connection, then you use options as a connection, if you want more features, use the following:


  • acquireTimeout: The milliseconds before a timeout occurs during the connection acquisition. This was slightly different fromconnectTimeout, because acquiring a pool connection does does always involve making a connection. (Default:10000)
  • waitForConnections: Determines the pool ' s action when no connections is available and the limit has been reached. Iftrue, the pool would queue the connection request and call it when one becomes available. Iffalse, the pool would immediately call back with an error. (Default:true)
  • connectionLimit: The maximum number of connections to create at once. (Default:10)
  • queueLimit: The maximum number of connection requests the pool would queue before returning an error fromgetConnection. If set0to, there are no limit to the number of queued connection requests. (Default:0)
Pool eventsconnection


The pool would emit aconnectionevent when a new connection is made within the pool. If you need to set session variables on the connection before it gets used, you can listen to theconnectionevent.

 
 
pool.on(‘connection‘, function (connection) {
  connection.query(‘SET SESSION auto_increment_increment=1‘)
});
Enqueue


The pool would emit anenqueueevent when a callback have been queued to wait for an available connection.


 
pool.on(‘enqueue‘, function () {
  console.log(‘Waiting for available connection slot‘);
});
Closing all the connections in a poolclosing all the connections in a pool


When you were done using the pool, you had to end all the connections or the node. js Event loop would stay active until the Connections is closed by the MySQL server. This was typically done if the pool was used in a script or when trying to gracefully shutdown a server. To end all the connections in the pool with the method on theendpool:


pool.end(function (err) {
  // all connections in the pool have ended
});



Theendmethod takes an optional callback so can use to know once all the connections has ended. The connections end gracefully, so all pending queries would still complete and the time to end the pool would vary .



Once havepool.end()been called, and otherpool.getConnectionoperations can no longer be performed






Nodejs application MySQL (purely translation)


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.