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:[email protected]/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

时间: 2024-08-07 14:56:01

nodejs应用mysql(纯属翻译)的相关文章

Nodejs+express+mysql+百度BAE部署node后台

转载请注明出处:http://www.cnblogs.com/shamoyuu/p/node_bae.html 百度有一个应用引擎,价格非常便宜,Java的tomcat每天4毛钱,node每天2毛钱,我以前在上面搭建过一个JavaWeb的项目,今天来说说怎么搭建nodejs+express+mysql的后台. 首先打开console.bce.baidu.com,注册登录完成,然后新建一个应用引擎BAE如下图进行设置 目前基础版的BAE只支持node4.4.4,不过应该已经足够了.如果是用koa2

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

最近在入门nodejs,正好学习到了如何使用nodejs进行数据库的连接,觉得比较重要,便写一下随笔,简单地记录一下 使用在安装好node之后,我们可以使用npm命令,在项目的根目录,安装nodejs中的mysql模块 npm install mysql 在连接数据库之前,要先引入nodejs连接处理mysql的模块 var mysql = require('mysql'); 类似php连接mysql的方式,编写连接代码 //使用nodejs处理mysql的模块,使用创建连接方法,创建与mysq

nodejs连接mysql实例

1.在工程目录下运行npm install mysql安装用于nodejs的mysql模块: 2.创建db.js模块用于连接mysql,同时定义query查询方法: var mysql = require('mysql'); // 创建一个数据库连接池 var pool = mysql.createPool({ connectionLimit: 50, host: 'localhost', user: 'admin', password: '123456', database: 'rp-test

nodeJS连接MySQL数据库

nodeJS连接MySQL数据库,首先创建一个数据库及表.如下: create databases node; create table test( id int AUTO_INCREMENT PRIMARY KEY , name char(50) )ENGINE=InnoDB DEFAULT CHARSET=utf8; 安装MySQL驱动: $ npm install mysql 下面是nodeJS代码: var sys = require('util'); console.log('正在连接

NodeJS+Express+MySQL开发小记(2):服务器部署

http://borninsummer.com/2015/06/17/notes-on-developing-nodejs-webapp/ NodeJS+Express+MySQL开发小记(1)里讲过在本地搭建 NodeJS 网站的若干细节.本人最近在阿里云服务器上面按最低配租了4个月的云服务器,所以想试着把这个项目部署到云上.云服务器操作系统是Ubuntu 14.04 LTS.之前一直在Windows下做开发,对于Linux下的环境搭建.配置还不是很熟悉,搭建的过程中学到很多东西. 本文简单记

Nodejs连接MySQL&&实现unity中的登陆注册功能

MySQL是一款常用的开源数据库产品,通常也是免费数据库的首选.查了一下NPM列表,发现Nodejs有13库可以访问MySQL,felixge/node-mysql似乎是最受关注项目,我也决定尝试用一下. 要注意名字,"felixge/node-mysql"非"node-mysql",安装目录 1. node-mysql介绍 felixge/node-mysql是一个纯nodejs的用javascript实现的一个MySQL客户端程序.felixge/node-my

学习Nodejs之mysql

学习Nodejs连接mysql数据库: 1.先安装mysql数据库 npm install mysql 2.测试连接数据库: var sql = require("mysql"); var db = sql.createConnection({host:"localhost",ure:"root",password:"",database:"test"}); db.query("select *

nodejs连接mysql

首先需要安装nodejs 的mysql包 npm install mysql 手动添加数据库依赖: 在安装nodejs目录下的node_modules\npm下package.json的dependencies中新增, "mysql":"latest" 例如: 安装目录图 配置 编写nodejs与mysql交互的代码 var mysql = require('mysql'); var TEST_DATABASE = 'test'; var TEST_TABLE =

Nodejs与MySQL交互(felixge/node-mysql)

Nodejs与MySQL交互(felixge/node-mysql) - porschev 原文  http://www.cnblogs.com/zhongweiv/p/nodejs_mysql.html 简介和安装 Node.js与MySQL交互操作有很多库,具体可以在 https://www.npmjs.org/search?q=mysql   查看. 我选择了felixge/node-mysql,用的人比较多,先随大溜看看它的使用, 暂时没有太过纠结于各库之间的执行性能问题 ,对其它库有研