Chinaunix首页 | 论坛 | 博客
  • 博客访问: 53285
  • 博文数量: 48
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 260
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-12 11:48
文章分类
文章存档

2016年(48)

我的朋友

分类: JavaScript

2016-10-24 17:04:45

mysql

A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.

     

点击(此处)折叠或打开

  1. $ npm install mysql

 For information about the previous 0.9.x releases, visit the .

Sometimes I may also ask you to install the latest version from Github to check if a bugfix is working. In this case, please do:

 

点击(此处)折叠或打开

  1. $ npm install felixge/node-mysql

 

This is a node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.

Here is an example on how to use it:

 

点击(此处)折叠或打开

  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection({
  3.   host : 'localhost',
  4.   user : 'me',
  5.   password : 'secret',
  6.   database : 'my_db'
  7. });
  8.  
  9. connection.connect();
  10.  
  11. connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  12.   if (err) throw err;
  13.  
  14.   console.log('The solution is: ', rows[0].solution);
  15. });
  16.  
  17. connection.end();

From this example, you can learn the following:

  • Every method you invoke on a connection is queued and executed in sequence.
  • Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

Thanks goes to the people who have contributed code to this module, see the .

Additionally I'd like to thank the following people:

  •  (Oracle) - for helping me with protocol questions.
  • Ulf Wendel (Oracle) - for helping me with protocol questions.

The following companies have supported this project financially, allowing me to spend more time on it (ordered by time of contribution):

  •  (my startup, we do file uploading & video encoding as a service, check it out)
  •  (they are )
  •  (they are )

If you are interested in sponsoring a day or more of my time, please .

If you'd like to discuss this module, or ask questions about it, please use one of the following:

  • Mailing list
  • IRC Channel: #node.js (on freenode.net, I pay attention to any message including the term mysql)

The recommended way to establish a connection is this:

点击(此处)折叠或打开

  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection({
  3.   host : 'example.org',
  4.   user : 'bob',
  5.   password : 'secret'
  6. });
  7.  
  8. connection.connect(function(err) {
  9.   if (err) {
  10.     console.error('error connecting: ' + err.stack);
  11.     return;
  12.   }
  13.  
  14.   console.log('connected as id ' + connection.threadId);
  15. });


However, a connection can also be implicitly established by invoking a query:


点击(此处)折叠或打开

  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection(...);
  3.  
  4. connection.query('SELECT 1', function(err, rows) {
  5.   // connected! (unless `err` is set)
  6. });

Depending on how you like to handle your errors, either method may be appropriate. Any type of connection error (handshake or network) is considered a fatal error, see the  section for more information.

When establishing a connection, you can set the following 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 . (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 ifsupportBigNumbers is disabled.
  • dateStrings: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date objects. (Default:false)
  • debug: Prints protocol details to stdout. (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.
  • ssl: object with ssl parameters or a string containing name of ssl profile. See .

In addition to passing these options as an object, you can also use a url string. For example:


点击(此处)折叠或打开

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

Note: The query values are first attempted to be parsed as JSON, and if that fails assumed to be plaintext strings.

The ssl option in the connection options takes a string or an object. When given a string, it uses one of the predefined SSL profiles included. The following profiles are included:

  • "Amazon RDS": this profile is for connecting to an Amazon RDS server and contains the certificates from  and 

When connecting to other servers, you will need to provide an object of options, in the same format as . Please note the arguments expect a string of the certificate, not a file name to the certificate. Here is a simple example:


点击(此处)折叠或打开

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

You can also connect to a MySQL server without properly providing the appropriate CA to trust. You should not do this.


点击(此处)折叠或打开

  1. var connection = mysql.createConnection({
  2.   host : 'localhost',
  3.   ssl : {
  4.     // DO NOT DO THIS
  5.     // set up your ca correctly to trust the connection
  6.     rejectUnauthorized: false
  7.   }
  8. });

There are two ways to end a connection. Terminating a connection gracefully is done by calling the end() method:


点击(此处)折叠或打开

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

This will make sure all previously enqueued queries are still before sending a COM_QUIT packet to the MySQL server. If a fatal error occurs before theCOM_QUIT packet can be sent, an err argument will be provided to the callback, but the connection will be terminated regardless of that.

An alternative way to end the connection is to call the destroy() method. This will cause an immediate termination of the underlying socket. Additionally destroy() guarantees that no more events or callbacks will be triggered for the connection.

 

点击(此处)折叠或打开

  1. connection.destroy();

 Unlike end() the destroy() method does not take a callback argument.

Use pool directly.


点击(此处)折叠或打开

  1. var mysql = require('mysql');
  2. var pool = mysql.createPool({
  3.   connectionLimit : 10,
  4.   host : 'example.org',
  5.   user : 'bob',
  6.   password : 'secret',
  7.   database : 'my_db'
  8. });
  9.  
  10. pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  11.   if (err) throw err;
  12.  
  13.   console.log('The solution is: ', rows[0].solution);
  14. });

Connections can be pooled to ease sharing a single connection, or managing multiple connections.


点击(此处)折叠或打开

  1. var mysql = require('mysql');
  2. var pool = mysql.createPool({
  3.   host : 'example.org',
  4.   user : 'bob',
  5.   password : 'secret',
  6.   database : 'my_db'
  7. });
  8.  
  9. pool.getConnection(function(err, connection) {
  10.   // connected! (unless `err` is set)
  11. });

When you are done with a connection, just call connection.release() and the connection will return to the pool, ready to be used again by someone else.


点击(此处)折叠或打开

  1. var mysql = require('mysql');
  2. var pool = mysql.createPool(...);
  3.  
  4. pool.getConnection(function(err, connection) {
  5.   // Use the connection
  6.   connection.query( 'SELECT something FROM sometable', function(err, rows) {
  7.     // And done with the connection.
  8.     connection.release();
  9.  
  10.     // Don't use the connection here, it has been returned to the pool.
  11.   });
  12. });

If you would like to close the connection and remove it from the pool, use connection.destroy() instead. The pool will create a new connection the next time one is needed.

Connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. Connections are also cycled round-robin style, with connections being taken from the top of the pool and returning to the bottom.

When a previous connection is retrieved from the pool, a ping

wemall 开源微商城 ,微信商城,商城源码,三级分销,微生鲜,微水果,微外卖,微订餐---专业的o2o系统 wemall地址:

代码详情:

阅读(703) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~