原文点击这里

目录

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

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. JavaWeb学习笔记--filter开发

    介绍自定义的Filter类必须实现Filter接口,并且实现Filter接口定义的init() doFilter() destory()方法.其中init为初始化,destory为销毁 doFilte ...

  2. ubuntu12.04安装jdk-7u79-linux-i586.tar.gz

    第一步:下载jdk-7u79-linux-i586.tar.gz 1.wget -c http://download.oracle.com/otn-pub/java/jdk/7/jdk-7-linux ...

  3. OC高级编程——深入block,如何捕获变量,如何存储在堆上

    OC高级编程——深入block,如何捕获变量,如何存储在堆上   首先先看几道block相关的题目 这是一篇比较长的  博文 ,前部分是block的测试题目,中间是block的语法.特性,block讲 ...

  4. shell编程技术之-基础知识

    一.脚本结构 linux下shell的脚本,是将一系列命令序列写在一个文本文件,而这个文本文件时可执行的.相对命令行来说,开发效率提高.因此他的构架有2部分构成#!和命令序列.其中#!指明此脚本是用哪 ...

  5. Detecting an Ajax request in PHP

    1:index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

  6. 智能卡 ATR解析

    如果终端不支持IC卡支持的其它传输协议以及传输参数值,IC卡应该有能力用基本ATR定义的模式和终端进行交互. 终端如果无法满足IC卡回送ATR中定义的传输模式,将发送一个热复位信号,或将IC卡置为静止 ...

  7. AIR检测网络

    package com.juyou.util.net { import flash.events.StatusEvent; import flash.net.URLRequest; import ai ...

  8. 打开首页老是加载themes.googleusercontent.com_Wopus问答

    打开首页老是加载themes.googleusercontent.com_Wopus问答 打开首页老是加载themes.googleusercontent.com

  9. Decorator学习笔记

    初学者,自己的理解,请各位前辈不吝指正! Decorator,装饰模式,设计模式之一,谈谈我的理解,装饰这个词在我概念中就是给某个事物加上一些美丽的外表,把它变得更加完美.但是装饰是可以随时改变的,可 ...

  10. 第25讲 UI组件之 AlertDialog 的各种实现

    第25讲 UI组件之AlertDialog 的各种实现 对话框(Dialog)是程序运行中的弹出窗口,例如当用户要删除一个联系方式时,会弹出一个对话框. Android提供了多种对话框:警告对话框(A ...