nodejs应用mysql(纯属翻译)

原文点击这里

目录

Install

$ npm install mysql

Introduction

nodejs驱动mysql。 ①js写的 ②还不需要编译 ③100%MIT许可

下面给出一个简单的例子:

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();

 从上面的栗子中,你可以学到下面2点:

  • 你在生成的同一个connection下,调用方法,都将以队列的形式排队按顺序执行。 
  • 你可以用end()来关闭connection, 这个方法的好处是,在给mysql服务器发送一个终止的信号量前,将队列里剩余的查询语句全部执行完.

Establishing connections

官方推荐下面这种方式建立一个链接(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);
});

当然,创建一个connection其实也隐藏在一个query语句里:

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

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

上面2种方法都不错,你可以任选其一来处理错误。任何链接上的错误(handshake or network)都被认为是致命的错误。更多关于Error Handling 。

Connection options

建立一个链接,你可以配置下面选项:

  • host: The hostname of the database you are 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 host and port are ignored.
  • user: The MySQL user to authenticate as.
  • password: The password of that MySQL user.
  • database: Name of the database to use for this connection (Optional).
  • charset: The charset for the connection. This is called "collation" in the SQL-level of MySQL (like utf8_general_ci). If a SQL-level charset is specified (like utf8mb4) then the default 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 that ask for the old (insecure) authentication method. (Default: false)
  • typeCast: Determines if column values should be 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: false).
  • bigNumberStrings: Enabling both supportBigNumbers and bigNumberStrings forces big numbers (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: false). Enabling supportBigNumbers but leaving bigNumberStrings disabled will return big numbers as String objects only when they cannot be accurately represented with JavaScript Number objects (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as Number objects. This option is ignored if supportBigNumbers is disabled.
  • dateStrings: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date objects. Can be true/false or an array of type names to keep as strings. (Default: false)
  • debug: Prints protocol details to stdout. Can be true/false or an array of packet type names that should be printed. (Default: false)
  • trace: Generates stack traces on Error to include call site of 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 ssl profile. See SSL options.

另外,你除了可以传递一个Object作为options的载体,你还可以选择url的方式:

 var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700'); 

 

注意:url里query 的值首先应该被试图解析成 JSON,如果解析失败,只能认为是普通的文本字符串。

SSL options

配置 ssl 选项可以是 a string or an object.如果是 string ,他会使用一个预先定义好的SSL文件配置,以下概要文件包括:

如果你要链接到其他服务器,你需要传Object作为options.格式类型是和crypto.createCredentials 一样的。需要注意的是,参数证书内容的字符串,而不是证书的名字:

 var connection = mysql.createConnection({ host : 'localhost', ssl : { ca : fs.readFileSync(__dirname + '/mysql-ca.crt') } }); 

 

当然你也可以连接到一个MYSQL服务器,这样你可以不需要提供合适的CA。但你不可以这样处理:

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

Terminating connections

终止链接,有2个种方式,但是采用end() 是比较优雅的:

 

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

 

它将保证所有已经在队列里的queries 会继续执行,最后再发送 COM_QUIT 包给MYSQL 服务器。如果在发送 COM_QUIT 包之前就出现了致命错误(handshake or network),就会给提供的callback里传入一个 err 参数。 但是,不管有没有错误,connection 都会照常中断。

 

另外一种就是  destroy()。 它其实是中断底层socket。

 connection.destroy(); 

 

end() 不同的是,destroy()是不会有回调的,当然就更不会产生 err 作为参数咯。

 

Pooling connections

与其你一个一个的管理connection,不如创建一个连接池,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);
});

 

池化使我们更好的操控单个conenction或者管理多个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)
});

当你完成操作的时候,你只需要调用 connection.release(),那这个 connection就会返回pool中,等待别人使用:

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.
  });
});

如果你就是想关闭这个connection,并且将它移除 pool,那就要使用connection.destroy().那pool将会重新生成一个新的conenction等待下次使用。

 

我们知道池化的都是懒加载的。如果你配置你的pool上限是100个connection,但是只是需要同时用了5个,那pool就生成5个,不会多生成connection,另外,connection是采用 round-robin 的方式循环的,从顶取出,返回到底部。

从池中检索到的前一个连接时,一个ping包会发送到服务器来确定这个链接是否是好的。

 

Pool options

options as a connection. 大致都差不多的,如果你只是创建一个connection,那你就用options as a connection,如果你想更多的一些特性就用下面几个:

  • acquireTimeout: The milliseconds before a timeout occurs during the connection acquisition. This is slightly different from connectTimeout, because acquiring a pool connection does not always involve making a connection. (Default: 10000)
  • waitForConnections: Determines the pool's action when no connections are available and the limit has been reached. If true, the pool will queue the connection request and call it when one becomes available. If false, the pool will 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 will queue before returning an error from getConnection. If set to 0, there is no limit to the number of queued connection requests. (Default: 0)

Pool events

connection

The pool will emit a connection event 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 the connection event.

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

enqueue

The pool will emit an enqueue event when a callback has 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 pool

Closing all the connections in a pool

When you are done using the pool, you have to end all the connections or the Node.js event loop will stay active until the connections are closed by the MySQL server. This is typically done if the pool is used in a script or when trying to gracefully shutdown a server. To end all the connections in the pool, use the end method on the pool:

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

The end method takes an optional callback that you can use to know once all the connections have ended. The connections end gracefully, so all pending queries will still complete and the time to end the pool will vary.

Once pool.end() has been called, pool.getConnection and other operations can no longer be performed

 

posted @ 2017-01-04 18:12  hdu胡恩超  阅读(398)  评论(0编辑  收藏  举报