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 ...
随机推荐
- IIS HTTP重定向到HTTPS
最近客户一个网站升级至HTTPS协议访问,但是为了用户输入,客户要求当用户输入的是HTTP协议时,能自动定向到HTTPS,类似百度网站,当你输入www.baidu.com并回车后,地址栏自动变成了ht ...
- 天兔(Lepus)监控系统快速安装部署
Lepus安装需要Lamp环境,Lamp环境的安装个人认为比较费劲,XAMPP的一键部署LAMP环境省心省力, lepus官网手册也建议采用XAMPP的方式安装,lepus也是在XAMPP上进行研发的 ...
- 管理维护Replica Sets
1.读写分离 有一些第三方的工具,提供了一些可以让数据库进行读写分离的工具.我们现在是否有一个疑问,从库要是能进行查询就更好了,这样可以分担主库的大量的查询请求. 1. 先向主库中插入一条测试数据 2 ...
- spring mvc 引用 jasper JasperReportsHtmlView的nullpx图片问题
spring mvc 引用 jasper JasperReportsHtmlView的nullpx图片问题 参考:http://stackoverflow.com/questions/1168633 ...
- Spring MVC DispatcherServlet绑定多种URL
需要学习的内容: http://my.oschina.net/shishuifox/blog/215617 当前的处理方式,在web.xml中配置: <servlet> <servl ...
- C#如何给PDF文档添加注释
整理文档时,我们可能会需要在一些或一段文字上添加注释加以说明,那如何以编程的方式实现呢?本文将实例讲述C#中如何使用免费组件给PDF文档添加文本注释,包括自由文本注释.自由文本注释能允许我们自定义它的 ...
- IEcss样式,行高的问题
input的文本内容显示一定要用line-height,不然会出现内容错位的问题
- [Scoi2010]游戏
游戏 Time Limit:5000MS Memory Limit:165888KB 64bit IO Format:%lld & %llu Submit Status Pra ...
- iOS深入学习之Weak关键字介绍
iOS深入学习之Weak关键字介绍 前言 从大二的开始接触OC就用到了weak属性修饰词,但是当时只是知道如何去用这个关键字:防止循环引用.根本没有深入地去了解它. 在刚来北京的时候面试过程中也常常考 ...
- HTTP学习目录
前面的话 除了HTML.CSS.javascript这三门前端基础知识之外,HTTP恐怕是前端工程师最需要掌握的知识了,它是前端和后端沟通的桥梁,前端工程师需要能够调试HTTP.修复网络传输中可能遇到 ...