nodejs应用mysql(纯属翻译)
目录
- 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 usedhostandportare 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 (likeutf8_general_ci). If a SQL-level charset is specified (likeutf8mb4) 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 bothsupportBigNumbersandbigNumberStringsforces big numbers (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default:false). EnablingsupportBigNumbersbut leavingbigNumberStringsdisabled 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 ifsupportBigNumbersis disabled.dateStrings: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then inflated into JavaScript Date objects. Can betrue/falseor an array of type names to keep as strings. (Default:false)debug: Prints protocol details to stdout. Can betrue/falseor an array of packet type names that should be printed. (Default:false)trace: Generates stack traces onErrorto 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文件配置,以下概要文件包括:
"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 fromconnectTimeout, 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. Iftrue, the pool will queue the connection request and call it when one becomes available. Iffalse, 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 fromgetConnection. If set to0, 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(纯属翻译)的更多相关文章
- nodejs项目mysql使用sequelize支持存储emoji
nodejs项目mysql使用sequelize支持存储emoji 本篇主要记录nodejs项目阿里云mysql如何支持存储emoji表情. 因由 最近项目遇到用户在文本输入emoji进行存储的时候导 ...
- 学习Nodejs之mysql
学习Nodejs连接mysql数据库: 1.先安装mysql数据库 npm install mysql 2.测试连接数据库: var sql = require("mysql"); ...
- nodejs+express+mysql 增删改查
之前,一直使用的是nodejs+thinkjs来完成自己所需的项目需求,而对于nodejs中另外一中应用框架express却了解的少之又少,这两天就简单的了解了一下如何使用express来做一些数据库 ...
- Nodejs连接mysql
1.首先需要安装nodejs 的mysql包 npm install mysql 2.编写nodejs与mysql交互的代码 var mysql = require('mysql'); var TES ...
- nodejs连接mysql并进行简单的增删查改
最近在入门nodejs,正好学习到了如何使用nodejs进行数据库的连接,觉得比较重要,便写一下随笔,简单地记录一下 使用在安装好node之后,我们可以使用npm命令,在项目的根目录,安装nodejs ...
- nodejs 操作mysql
这篇文章主要介绍了nodejs中操作mysql数据库示例,本文演示了如何在NodeJS中创建创建mysql连接.mysql数据库.插入数据.查询数据等功能,需要的朋友可以参考下 引言: 继前面的No ...
- nodejs连接mysql实例
1.在工程目录下运行npm install mysql安装用于nodejs的mysql模块: 2.创建db.js模块用于连接mysql,同时定义query查询方法: var mysql = requi ...
- rhel6.4 安装nodejs和Mysql DB服务
rhel6.4 安装nodejs和Mysql DB服务 安装好redhat6.4虚拟机后, 安装软件: # yum install gcc-c++ openssl-devel Loaded plugi ...
- 用Nodejs连接MySQL
转载,原地址:http://blog.fens.me/nodejs-mysql-intro/ 前言 MySQL是一款常用的开源数据库产品,通常也是免费数据库的首选.查了一下NPM列表,发现Nodejs ...
随机推荐
- MySQL锁等待分析【1】
场景: 昨天业务系统上遇到了数据库慢的问题(对dcsdba.og_file_audit表的insert 慢&超时).分析后定位到是由于锁等待造成的.分析过程如下: 1.执行show proce ...
- 请问FMX手机app多个窗体如何嵌入同一个窗体?
app有多个不同窗体,均调用相同的一个小窗体,因显示同一样的东西,如grid:如果每个窗体都重复加 小窗体的界面和代码,非常麻烦,而且编译后体积也很大: vcl中这样就行: Form1:=TForm ...
- universal image loader在listview/gridview中滚动时重复加载图片的问题及解决方法
在listview/gridview中使用UIL来display每个item的图片,当图片数量较多需要滑动滚动时会出现卡顿,而且加载过的图片再次上翻后依然会重复加载(显示设置好的加载中图片) 最近在使 ...
- javascript学习笔记——chrome等提示找不到“getElementsByTagName”的一种解决方法
最近学习是写了一个小网页,前台有个下拉框是通过后天的xml配置的,在写好代码后使用发现在IE9以及之前的IE浏览器都可以正常获取,但是IE10,chrome和firefox都会在获取一个标签时报get ...
- [置顶] 【原创分享】嵌入式linux应用之内核移植定制篇-前篇(linux-3.8.12 mini2440)--20130824
移植的话其实很早就做过了,不过那时用的友善定制的老版本2.6.32 驱动什么的全部弄好了,仅仅用默认配置而已.基本不用改动什么,很简单. 内核更新其实非常的快,今天我就用个3.8.12来移植. 当然, ...
- using 1.7 requires using android build tools version 19 or later
这意思大概是adt用了1.7,abt(android build tools)就要用19或更高,可是abt在哪设置呢,原来是在sdk manager中 之前我已安装的最高的abt是17,然后~~~,F ...
- 快速理解RequireJs
原文地址:http://www.tuicool.com/articles/jam2Anv RequireJs已经流行很久了,我们在项目中也打算使用它.它提供了以下功能: 声明不同js文件之间的依赖 可 ...
- SOA 新业务语言 新系统架构——什么是SOA
原文地址:http://blog.csdn.net/ichaos/archive/2008/01/20/2054377.aspx SOA的概念是Gartner在1996年提出来的,并于2002年12月 ...
- Zedboard甲诊opencv图像处理(三)
整个工程进展到这一步也算是不容易吧,但技术含量也不怎么高,中间乱起八糟的错误太烦人了,不管怎么样,现在面临了最大的困难吧,图像处理算法.算法确实不好弄啊,虽然以前整过,但都不是针对图像的. 现在的图像 ...
- css实现两端对齐~
今天做表单时遇到让上下两个字段对齐的情况,手机号码.用户名. 然后今天在网上找了找相关方法,发现确实是没有什么好的方法解决,特别是当需要兼容的时候.找到了两个我觉得相对还不错的方法: 方法一.是在司徒 ...