原文点击这里

目录

Install

  1. $ npm install mysql

Introduction

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

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

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

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

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

Establishing connections

官方推荐下面这种方式建立一个链接(connection):

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

当然,创建一个connection其实也隐藏在一个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. });

上面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。但你不可以这样处理:

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

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.

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

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

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

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

如果你就是想关闭这个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.

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

enqueue

The pool will emit an enqueue event when a callback has been queued to wait for an available connection.

  1. pool.on('enqueue', function () {
  2. console.log('Waiting for available connection slot');
  3. });

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:

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

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(纯属翻译)的更多相关文章

  1. nodejs项目mysql使用sequelize支持存储emoji

    nodejs项目mysql使用sequelize支持存储emoji 本篇主要记录nodejs项目阿里云mysql如何支持存储emoji表情. 因由 最近项目遇到用户在文本输入emoji进行存储的时候导 ...

  2. 学习Nodejs之mysql

    学习Nodejs连接mysql数据库: 1.先安装mysql数据库 npm install mysql 2.测试连接数据库: var sql = require("mysql"); ...

  3. nodejs+express+mysql 增删改查

    之前,一直使用的是nodejs+thinkjs来完成自己所需的项目需求,而对于nodejs中另外一中应用框架express却了解的少之又少,这两天就简单的了解了一下如何使用express来做一些数据库 ...

  4. Nodejs连接mysql

    1.首先需要安装nodejs 的mysql包 npm install mysql 2.编写nodejs与mysql交互的代码 var mysql = require('mysql'); var TES ...

  5. nodejs连接mysql并进行简单的增删查改

    最近在入门nodejs,正好学习到了如何使用nodejs进行数据库的连接,觉得比较重要,便写一下随笔,简单地记录一下 使用在安装好node之后,我们可以使用npm命令,在项目的根目录,安装nodejs ...

  6. nodejs 操作mysql

    这篇文章主要介绍了nodejs中操作mysql数据库示例,本文演示了如何在NodeJS中创建创建mysql连接.mysql数据库.插入数据.查询数据等功能,需要的朋友可以参考下  引言: 继前面的No ...

  7. nodejs连接mysql实例

    1.在工程目录下运行npm install mysql安装用于nodejs的mysql模块: 2.创建db.js模块用于连接mysql,同时定义query查询方法: var mysql = requi ...

  8. rhel6.4 安装nodejs和Mysql DB服务

    rhel6.4 安装nodejs和Mysql DB服务 安装好redhat6.4虚拟机后, 安装软件: # yum install gcc-c++ openssl-devel Loaded plugi ...

  9. 用Nodejs连接MySQL

    转载,原地址:http://blog.fens.me/nodejs-mysql-intro/ 前言 MySQL是一款常用的开源数据库产品,通常也是免费数据库的首选.查了一下NPM列表,发现Nodejs ...

随机推荐

  1. Spring MVC 和Struts2对比

    Spring MVC和Struts2的区别: 1. 机制:spring mvc的入口是servlet,而struts2是filter,这样就导致了二者的机制不同. ​2. 性能:spring会稍微比s ...

  2. Codeforces 525E Anya and Cubes

    http://codeforces.com/contest/525/problem/E 题意: 有n个方块,上面写着一些自然数,还有k个感叹号可用.k<=n 你可以选任意个方块,然后选一些贴上感 ...

  3. 开源的Owin 的身份验证支持 和跨域支持

    http://identitymodel.codeplex.com/ https://identityserver.github.io/ Windows Identity Foundation 6.1 ...

  4. logstash 发送慢页面到zabbix告警

    input { file { type => "zj_frontend_access" path => ["/data01/applog_backup/zjz ...

  5. 构建一个基于 Spring 的 RESTful Web Service

    本文详细介绍了基于Spring创建一个“hello world” RESTful web service工程的步骤. 目标 构建一个service,接收如下HTTP GET请求: http://loc ...

  6. 传阿里整合资源,进军O2O市场

    阿里巴巴对于本地生活市场,以及O2O领域始终虎视眈眈.从最早的融合口碑网,到最近阶段推出淘宝点点.收购高德地图等一系列app产品,其整合线上线下消费市场的野心已十分明显. 今年年初,阿里巴巴集团重新进 ...

  7. Ajax--xml格式及注意事项

    <?xml version='1.0' ?>//整个标签必须顶格写,version='1.0'是xml的版本号 <Info>//只能有且只有一个根作为最外层标签 <n1& ...

  8. java_重写与重载的区别

    重写与重载的区别 重载(Overloading)和重写(Overriding)是Java中两个比较重要的概念.但是对于新手来说也比较容易混淆.本文通过两个简单的例子说明了他们之间的区别. 定义 重载 ...

  9. JSP简单练习-数组应用实例

    <%@ page contentType="text/html; charset=gb2312" %> <html> <body> <% ...

  10. [RxJS] Handling a Complete Stream with Reduce

    When a stream has completed, you often need to evaluate everything that has happened while the strea ...