UNPKG

11.7 kBMarkdownView Raw
1## Node MySQL 2
2
3[![Greenkeeper badge](https://badges.greenkeeper.io/sidorares/node-mysql2.svg)](https://greenkeeper.io/)
4[![NPM Version][npm-image]][npm-url]
5[![NPM Downloads][downloads-image]][downloads-url]
6[![Node.js Version][node-version-image]][node-version-url]
7[![Linux Build][travis-image]][travis-url]
8[![Windows Build][appveyor-image]][appveyor-url]
9[![License][license-image]][license-url]
10
11English | [简体中文](./documentation_zh-cn/)
12
13> MySQL client for Node.js with focus on performance. Supports prepared statements, non-utf8 encodings, binary log protocol, compression, ssl [much more](https://github.com/sidorares/node-mysql2/tree/master/documentation)
14
15__Table of contents__
16
17 - [History and Why MySQL2](#history-and-why-mysql2)
18 - [Installation](#installation)
19 - [First Query](#first-query)
20 - [Using Prepared Statements](#using-prepared-statements)
21 - [Using connection pools](#using-connection-pools)
22 - [Using Promise Wrapper](#using-promise-wrapper)
23 - [API and Configuration](#api-and-configuration)
24 - [Documentation](#documentation)
25 - [Acknowledgements](#acknowledgements)
26 - [Contributing](#contributing)
27
28## History and Why MySQL2
29
30MySQL2 project is a continuation of [MySQL-Native][mysql-native]. Protocol parser code was rewritten from scratch and api changed to match popular [mysqljs/mysql][node-mysql]. MySQL2 team is working together with [mysqljs/mysql][node-mysql] team to factor out shared code and move it under [mysqljs][node-mysql] organisation.
31
32MySQL2 is mostly API compatible with [mysqljs][node-mysql] and supports majority of features. MySQL2 also offers these additional features
33
34 - Faster / Better Performance
35 - [Prepared Statements](https://github.com/sidorares/node-mysql2/tree/master/documentation/Prepared-Statements.md)
36 - MySQL Binary Log Protocol
37 - [MySQL Server](https://github.com/sidorares/node-mysql2/tree/master/documentation/MySQL-Server.md)
38 - Extended support for Encoding and Collation
39 - [Promise Wrapper](https://github.com/sidorares/node-mysql2/tree/master/documentation/Promise-Wrapper.md)
40 - Compression
41 - SSL and [Authentication Switch](https://github.com/sidorares/node-mysql2/tree/master/documentation/Authentication-Switch.md)
42 - [Custom Streams](https://github.com/sidorares/node-mysql2/tree/master/documentation/Extras.md)
43 - [Pooling](#using-connection-pools)
44
45## Installation
46
47MySQL2 is free from native bindings and can be installed on Linux, Mac OS or Windows without any issues.
48
49```bash
50npm install --save mysql2
51```
52
53## First Query
54
55```js
56// get the client
57const mysql = require('mysql2');
58
59// create the connection to database
60const connection = mysql.createConnection({
61 host: 'localhost',
62 user: 'root',
63 database: 'test'
64});
65
66// simple query
67connection.query(
68 'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
69 function(err, results, fields) {
70 console.log(results); // results contains rows returned by server
71 console.log(fields); // fields contains extra meta data about results, if available
72 }
73);
74
75// with placeholder
76connection.query(
77 'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
78 ['Page', 45],
79 function(err, results) {
80 console.log(results);
81 }
82);
83```
84
85## Using Prepared Statements
86
87With MySQL2 you also get the prepared statements. With prepared statements MySQL doesn't have to prepare plan for same query everytime, this results in better performance. If you don't know why they are important, please check these discussions
88
89- [How prepared statements can protect from SQL Injection attacks](http://stackoverflow.com/questions/8263371/how-can-prepared-statements-protect-from-sql-injection-attacks)
90
91MySQL provides `execute` helper which will prepare and query the statement. You can also manually prepare / unprepare statement with `prepare` / `unprepare` methods.
92
93```js
94// get the client
95const mysql = require('mysql2');
96
97// create the connection to database
98const connection = mysql.createConnection({
99 host: 'localhost',
100 user: 'root',
101 database: 'test'
102});
103
104// execute will internally call prepare and query
105connection.execute(
106 'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
107 ['Rick C-137', 53],
108 function(err, results, fields) {
109 console.log(results); // results contains rows returned by server
110 console.log(fields); // fields contains extra meta data about results, if available
111
112 // If you execute same statement again, it will be picked from a LRU cache
113 // which will save query preparation time and give better performance
114 }
115);
116```
117
118## Using connection pools
119
120Connection pools help reduce the time spent connecting to the MySQL server by reusing a previous connection, leaving them open instead of closing when you are done with them.
121
122This improves the latency of queries as you avoid all of the overhead that comes with establishing a new connection.
123
124```js
125// get the client
126const mysql = require('mysql2');
127
128// Create the connection pool. The pool-specific settings are the defaults
129const pool = mysql.createPool({
130 host: 'localhost',
131 user: 'root',
132 database: 'test',
133 waitForConnections: true,
134 connectionLimit: 10,
135 maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
136 idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
137 queueLimit: 0
138});
139```
140The pool does not create all connections upfront but creates them on demand until the connection limit is reached.
141
142You can use the pool in the same way as connections (using `pool.query()` and `pool.execute()`):
143```js
144// For pool initialization, see above
145pool.query("SELECT field FROM atable", function(err, rows, fields) {
146 // Connection is automatically released when query resolves
147})
148```
149
150Alternatively, there is also the possibility of manually acquiring a connection from the pool and returning it later:
151```js
152// For pool initialization, see above
153pool.getConnection(function(err, conn) {
154 // Do something with the connection
155 conn.query(/* ... */);
156 // Don't forget to release the connection when finished!
157 pool.releaseConnection(conn);
158})
159```
160
161## Using Promise Wrapper
162
163MySQL2 also support Promise API. Which works very well with ES7 async await.
164
165<!--eslint-disable-next-block-->
166```js
167async function main() {
168 // get the client
169 const mysql = require('mysql2/promise');
170 // create the connection
171 const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
172 // query database
173 const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);
174}
175```
176
177MySQL2 use default `Promise` object available in scope. But you can choose which `Promise` implementation you want to use
178
179<!--eslint-disable-next-block-->
180```js
181// get the client
182const mysql = require('mysql2/promise');
183
184// get the promise implementation, we will use bluebird
185const bluebird = require('bluebird');
186
187// create the connection, specify bluebird as Promise
188const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test', Promise: bluebird});
189
190// query database
191const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);
192```
193
194MySQL2 also exposes a .promise() function on Pools, so you can create a promise/non-promise connections from the same pool
195```js
196async function main() {
197 // get the client
198 const mysql = require('mysql2');
199 // create the pool
200 const pool = mysql.createPool({host:'localhost', user: 'root', database: 'test'});
201 // now get a Promise wrapped instance of that pool
202 const promisePool = pool.promise();
203 // query database using promises
204 const [rows,fields] = await promisePool.query("SELECT 1");
205```
206
207MySQL2 exposes a .promise() function on Connections, to "upgrade" an existing non-promise connection to use promise
208```js
209// get the client
210const mysql = require('mysql2');
211// create the connection
212const con = mysql.createConnection(
213 {host:'localhost', user: 'root', database: 'test'}
214);
215con.promise().query("SELECT 1")
216 .then( ([rows,fields]) => {
217 console.log(rows);
218 })
219 .catch(console.log)
220 .then( () => con.end());
221```
222
223## Array results
224
225If you have two columns with the same name, you might want to get results as an array rather than an object to prevent them from clashing. This is a deviation from the [Node MySQL][node-mysql] library.
226
227For example: `select 1 as foo, 2 as foo`.
228
229You can enable this setting at either the connection level (applies to all queries), or at the query level (applies only to that specific query).
230
231### Connection Option
232```js
233const con = mysql.createConnection(
234 { host: 'localhost', database: 'test', user: 'root', rowsAsArray: true }
235);
236
237```
238
239### Query Option
240
241```js
242con.query({ sql: 'select 1 as foo, 2 as foo', rowsAsArray: true }, function(err, results, fields) {
243 console.log(results) // will be an array of arrays rather than an array of objects
244 console.log(fields) // these are unchanged
245});
246
247```
248
249## API and Configuration
250
251MySQL2 is mostly API compatible with [Node MySQL][node-mysql]. You should check their API documentation to see all available API options.
252
253One known incompatibility is that `DECIMAL` values are returned as strings whereas in [Node MySQL][node-mysql] they are returned as numbers. This includes the result of `SUM()` and `AVG()` functions when applied to `INTEGER` arguments. This is done deliberately to avoid loss of precision - see https://github.com/sidorares/node-mysql2/issues/935.
254
255If you find any other incompatibility with [Node MySQL][node-mysql], Please report via Issue tracker. We will fix reported incompatibility on priority basis.
256
257## Documentation
258
259You can find more detailed documentation [here](https://github.com/sidorares/node-mysql2/tree/master/documentation). You should also check various code [examples](https://github.com/sidorares/node-mysql2/tree/master/examples) to understand advanced concepts.
260
261## Acknowledgements
262
263 - Internal protocol is written by @sidorares [MySQL-Native](https://github.com/sidorares/nodejs-mysql-native)
264 - Constants, SQL parameters interpolation, Pooling, `ConnectionConfig` class taken from [node-mysql](https://github.com/mysqljs/mysql)
265 - SSL upgrade code based on @TooTallNate [code](https://gist.github.com/TooTallNate/848444)
266 - Secure connection / compressed connection api flags compatible to [MariaSQL](https://github.com/mscdex/node-mariasql/) client.
267 - [Contributors](https://github.com/sidorares/node-mysql2/graphs/contributors)
268
269## Contributing
270
271Want to improve something in `node-mysql2`. Please check [Contributing.md](https://github.com/sidorares/node-mysql2/blob/master/Contributing.md) for detailed instruction on how to get started.
272
273
274[npm-image]: https://img.shields.io/npm/v/mysql2.svg
275[npm-url]: https://npmjs.org/package/mysql2
276[node-version-image]: http://img.shields.io/node/v/mysql2.svg
277[node-version-url]: http://nodejs.org/download/
278[travis-image]: https://img.shields.io/travis/sidorares/node-mysql2/master.svg?label=linux
279[travis-url]: https://travis-ci.org/sidorares/node-mysql2
280[appveyor-image]: https://img.shields.io/appveyor/ci/sidorares/node-mysql2/master.svg?label=windows
281[appveyor-url]: https://ci.appveyor.com/project/sidorares/node-mysql2
282[downloads-image]: https://img.shields.io/npm/dm/mysql2.svg
283[downloads-url]: https://npmjs.org/package/mysql2
284[license-url]: https://github.com/sidorares/node-mysql2/blob/master/License
285[license-image]: https://img.shields.io/npm/l/mysql2.svg?maxAge=2592000
286[node-mysql]: https://github.com/mysqljs/mysql
287[mysql-native]: https://github.com/sidorares/nodejs-mysql-native