KoaHub.JS基于Node.js开发的mysql的node.js驱动程序代码
mysql
A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.
mysql
Table of Contents
- 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
- Running tests
- Todo
Install
$ npm install mysql
For information about the previous 0.9.x releases, visit the v0.9 branch.
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:
$ 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:
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();
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.
Contributors
Thanks goes to the people who have contributed code to this module, see the GitHub Contributors page.
Additionally I'd like to thank the following people:
- Andrey Hristov (Oracle) - for helping me with protocol questions.
- Ulf Wendel (Oracle) - for helping me with protocol questions.
Sponsors
The following companies have supported this project financially, allowing me to spend more time on it (ordered by time of contribution):
- Transloadit (my startup, we do file uploading & video encoding as a service, check it out)
- Joyent
- pinkbike.com
- Holiday Extras (they are hiring)
- Newscope (they are hiring)
If you are interested in sponsoring a day or more of my time, please get in touch.
Community
If you'd like to discuss this module, or ask questions about it, please use one of the following:
- Mailing list: https://groups.google.com/forum/#!forum/node-mysql
- IRC Channel: #node.js (on freenode.net, I pay attention to any message including the term
mysql)
Establishing connections
The recommended way to establish a connection is this:
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);
});
However, a connection can also be implicitly established by invoking a query:
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) {
// connected! (unless `err` is set)
});
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 Error Handling section for more information.
Connection options
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 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] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5) (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. (Default:false)debug: Prints protocol details to stdout. (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, checkConnection Flags.ssl: object with ssl parameters or a string containing name of ssl profile. See SSL options.
In addition to passing these options as an object, you can also use a url string. For example:
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.
SSL options
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 https://rds.amazonaws.com/doc/rds-ssl-ca-cert.pem and https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem
When connecting to other servers, you will need to provide an object of options, in the same format as crypto.createCredentials. Please note the arguments expect a string of the certificate, not a file name to the certificate. Here is a simple example:
var connection = mysql.createConnection({
host : 'localhost',
ssl : {
ca : fs.readFileSync(__dirname + '/mysql-ca.crt')
}
});
You can also connect to a MySQL server without properly providing the appropriate CA to trust. You should not do this.
var connection = mysql.createConnection({
host : 'localhost',
ssl : {
// DO NOT DO THIS
// set up your ca correctly to trust the connection
rejectUnauthorized: false
}
});
Terminating connections
There are two ways to end a connection. Terminating a connection gracefully is done by calling the end() method:
connection.end(function(err) {
// The connection is terminated now
});
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.
connection.destroy();
Unlike end() the destroy() method does not take a callback argument.
Pooling connections
Use pool directly.
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);
});
Connections can be pooled to ease sharing a single connection, or managing multiple 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)
});
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.
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.
});
});
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地址:http://www.wemallshop.com
代码详情:http://js.koahub.com/home/feature/mysql
KoaHub.JS基于Node.js开发的mysql的node.js驱动程序代码的更多相关文章
- KoaHub平台基于Node.js开发的Koa 连接支付宝插件代码信息详情
KoaHub平台基于Node.js开发的Koa 链接支付宝插件代码信息详情 easy-alipay alipay payment & notification APIs easy-alipay ...
- KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架之koahub-yilianyun
koahub-yilianyun 微信易联云打印机接口 koahub-yilianyun易联云打印机node接口 Installation $ npm install koahub-yilianyun ...
- KoaHub.js可借助 Babel 编译稳定运行在 Node.js 环境上
koahubjs KoaHub.js -- 基于 Koa.js 平台的 Node.js web 快速开发框架.可以直接在项目里使用 ES6/7(Generator Function, Class, A ...
- 性能追击:万字长文30+图揭秘8大主流服务器程序线程模型 | Node.js,Apache,Nginx,Netty,Redis,Tomcat,MySQL,Zuul
本文为<高性能网络编程游记>的第六篇"性能追击:万字长文30+图揭秘8大主流服务器程序线程模型". 最近拍的照片比较少,不知道配什么图好,于是自己画了一个,凑合着用,让 ...
- 《Node.js+MongoDB+AngularJS Web开发》读书笔记及联想
总体介绍 <Node.js+MongoDB+AngularJS Web开发>,于2015年6月出版,是一本翻译过来的书,原书名为<Node.js,MongoDB and Angula ...
- 如何在 Android 安卓手机上运行 Node.js 应用 | 如何在安卓手机配置node开发环境
最近在学习js,由于没法随身携带笔记本电脑,在手机翻阅<JavaScript高级程序设计>时,时常想调试一下书中的代码.于是就有了,能否在手机上配置一个js开发环境.考虑到手机上的Chro ...
- [Node.js框架] 为什么要开发 Codekart 框架
两年前,在被php的$符号和字符串处理折磨得半夜骂娘之后,我义无反顾地决定:珍爱生命,远离php. 之后一直在寻找一门“完美的语言”,先后接触了Lisp.python.java.Ruby.Lisp几乎 ...
- 深入理解Node.js基于事件驱动的回调
回调和异步调用的关系 首先明确一点,回调并非是异步调用,回调是一种解决异步函数执行结果的处理方法.在异步调用,如果我们希望将执行的结果返回并且处理时,可以通过回调的方法解决.为了能够更好的区分回调和异 ...
- Node.js 命令行程序开发资料
Node.js 命令行程序开发教程http://www.ruanyifeng.com/blog/2015/05/command-line-with-node.html用Node.js创建命令行工具ht ...
随机推荐
- ViewFlipper的功能与用法
ViewFlipper组件继承了ViewAnimator,它可调用addView(View v)添加多个组件,一旦向ViewFlipper中添加了多个组件之后,ViewFlipper可使用动画控制多个 ...
- javascript获取整数随机数
javascript获取整数随机数 // 从4到10的随机数,|0是生成正整数 var numBars = Math.random()*6+4|0; 也可以通过右移0位(或者左移0位)进行取整 var ...
- Flex4 布局 元素index
Flex4 布局 元素index <?xml version="1.0" encoding="utf-8"?> <s:Application ...
- ZooKeepr日志清理
http://blog.csdn.net/xiaolang85/article/details/21184293
- mesos 资源分配
Mesos 资源分配 众所周知, Mesos在运行时使用wDRF( Dominant Resource Fairness)算法进行一级资源分配, 通过应用程序(Framework)运行时使用资源进行二 ...
- pycharm 修改新建文件时的头部模板(默认为__author__='...')
pycharm 修改新建文件时的头部模板 默认为__author__='...' [省略号是默认你的计算机名] 修改这个作者名的步骤: 依次点击:File->Settings->Ed ...
- Eclipse 报java.lang.UnsupportedClassVersionError: ("yourclass") bad major version at offset=6
报这个错误是指你的jar包或者class 的被编译的jdk版本比当前runtime的jdk版本高. 解决问题 1)如果是jar包,重新用jdk 1.6编译你的jar 包 2)如果是java文件或者项目 ...
- Hbase数据库安装
一.环境准备 1.Ubuntu14.04-server 2.ssh 3.jdk1.6 4.hbase-0.98.19-hadoop2-bin.tar.gz(下载地址http://www.apache. ...
- matlab 逻辑数组及其应用
这几天学习了matlab的逻辑数组功能,总的感觉就有两点: 第一,通过对原来的数组a进行逻辑判断后得到逻辑数组b 第二,逻辑数组进行某种运算符操作又回到原数组类型 第三,利用逻辑数组mask功能 测试 ...
- Ubuntu纯字符界面的一些设置
由于Ubuntu的纯字符界面不支持中文显示,所以进行了一些配置,为了更好的显示 1. 把环境语言配置为英文 在用户目录下的".bashrc"文件的结尾处添加以下内容,然后重新登录 ...