nodejs應用mysql(純屬翻譯)

來源:互聯網
上載者:User

標籤:user   switch   特性   with   exception   ati   選項   connected   initial   

原文點擊這裡

目錄
  • 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驅動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:[email protected]/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700‘); 

 

注意:url裡query 的值首先應該被試圖解析成 JSON,如果解析失敗,只能認為是普通的文本字串。

SSL options

配置 ssl 選項可以是 a string or an object.如果是 string ,他會使用一個預先定義好的SSL檔案配置,以下概要檔案包括:

  • "Amazon RDS": this profile is for connecting to an 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

如果你要連結到其他伺服器,你需要傳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 eventsconnection

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 poolClosing 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

 

nodejs應用mysql(純屬翻譯)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.