• Stars
    star
    4,062
  • Rank 10,704 (Top 0.3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated about 1 month ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

âš¡ fast mysqljs/mysql compatible mysql driver for node.js

Node MySQL 2

Greenkeeper badge NPM Version NPM Downloads Node.js Version Linux Build Windows Build License

English | 简体中文 | Português (BR)

MySQL client for Node.js with focus on performance. Supports prepared statements, non-utf8 encodings, binary log protocol, compression, ssl much more.

Table of contents

History and Why MySQL2

MySQL2 project is a continuation of MySQL-Native. Protocol parser code was rewritten from scratch and api changed to match popular mysqljs/mysql. MySQL2 team is working together with mysqljs/mysql team to factor out shared code and move it under mysqljs organisation.

MySQL2 is mostly API compatible with mysqljs and supports majority of features. MySQL2 also offers these additional features:

Installation

MySQL2 is free from native bindings and can be installed on Linux, Mac OS or Windows without any issues.

npm install --save mysql2

First Query

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// simple query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// with placeholder
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function(err, results) {
    console.log(results);
  }
);

Using Prepared Statements

With MySQL2 you also get the prepared statements. With prepared statements MySQL doesn't have to prepare plan for same query every time, this results in better performance. If you don't know why they are important, please check these discussions:

MySQL2 provides execute helper which will prepare and query the statement. You can also manually prepare / unprepare statement with prepare / unprepare methods.

// get the client
const mysql = require('mysql2');

// create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test'
});

// execute will internally call prepare and query
connection.execute(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Rick C-137', 53],
  function(err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available

    // If you execute same statement again, it will be picked from a LRU cache
    // which will save query preparation time and give better performance
  }
);

Using connection pools

Connection 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.

This improves the latency of queries as you avoid all of the overhead that comes with establishing a new connection.

// get the client
const mysql = require('mysql2');

// Create the connection pool. The pool-specific settings are the defaults
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  database: 'test',
  waitForConnections: true,
  connectionLimit: 10,
  maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
  idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
  queueLimit: 0,
  enableKeepAlive: true,
  keepAliveInitialDelay: 0
});

The pool does not create all connections upfront but creates them on demand until the connection limit is reached.

You can use the pool in the same way as connections (using pool.query() and pool.execute()):

// For pool initialization, see above
pool.query("SELECT `field` FROM `table`", function(err, rows, fields) {
  // Connection is automatically released when query resolves
});

Alternatively, there is also the possibility of manually acquiring a connection from the pool and returning it later:

// For pool initialization, see above
pool.getConnection(function(err, conn) {
  // Do something with the connection
  conn.query(/* ... */);
  // Don't forget to release the connection when finished!
  pool.releaseConnection(conn);
});

Using Promise Wrapper

MySQL2 also support Promise API. Which works very well with ES7 async await.

async function main() {
  // get the client
  const mysql = require('mysql2/promise');
  // create the connection
  const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test'});
  // query database
  const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);
}

MySQL2 use default Promise object available in scope. But you can choose which Promise implementation you want to use.

// get the client
const mysql = require('mysql2/promise');

// get the promise implementation, we will use bluebird
const bluebird = require('bluebird');

// create the connection, specify bluebird as Promise
const connection = await mysql.createConnection({host:'localhost', user: 'root', database: 'test', Promise: bluebird});

// query database
const [rows, fields] = await connection.execute('SELECT * FROM `table` WHERE `name` = ? AND `age` > ?', ['Morty', 14]);

MySQL2 also exposes a .promise() function on Pools, so you can create a promise/non-promise connections from the same pool.

async function main() {
  // get the client
  const mysql = require('mysql2');
  // create the pool
  const pool = mysql.createPool({host:'localhost', user: 'root', database: 'test'});
  // now get a Promise wrapped instance of that pool
  const promisePool = pool.promise();
  // query database using promises
  const [rows,fields] = await promisePool.query("SELECT 1");
}

MySQL2 exposes a .promise() function on Connections, to "upgrade" an existing non-promise connection to use promise.

// get the client
const mysql = require('mysql2');
// create the connection
const con = mysql.createConnection(
  {host:'localhost', user: 'root', database: 'test'}
);
con.promise().query("SELECT 1")
  .then( ([rows,fields]) => {
    console.log(rows);
  })
  .catch(console.log)
  .then( () => con.end());

Array Results

If 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 library.

For example: select 1 as foo, 2 as foo.

You can enable this setting at either the connection level (applies to all queries), or at the query level (applies only to that specific query).

Connection Level

const con = mysql.createConnection(
  { host: 'localhost', database: 'test', user: 'root', rowsAsArray: true }
);

Query Level

con.query({ sql: 'select 1 as foo, 2 as foo', rowsAsArray: true }, function(err, results, fields) {
  console.log(results); // in this query, results will be an array of arrays rather than an array of objects
  console.log(fields); // fields are unchanged
});

API and Configuration

MySQL2 is mostly API compatible with Node MySQL. You should check their API documentation to see all available API options.

One known incompatibility is that DECIMAL values are returned as strings whereas in 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 #935.

If you find any other incompatibility with Node MySQL, Please report via Issue tracker. We will fix reported incompatibility on priority basis.

Documentation

You can find more detailed documentation here. You should also check various code examples to understand advanced concepts.

Acknowledgements

  • Internal protocol is written by @sidorares MySQL-Native
  • Constants, SQL parameters interpolation, Pooling, ConnectionConfig class taken from node-mysql
  • SSL upgrade code based on @TooTallNate code
  • Secure connection / compressed connection api flags compatible to MariaSQL client.
  • Contributors

Contributing

Want to improve something in node-mysql2. Please check Contributing.md for detailed instruction on how to get started.

More Repositories

1

json-bigint

JSON.parse/stringify with bigints support
JavaScript
722
star
2

node-vim-debugger

node.js step by step debugging from vim
JavaScript
562
star
3

node-x11

X11 node.js network protocol client
JavaScript
518
star
4

vnc-over-gif

JavaScript
512
star
5

node-tick

node.js-runnable v8.log processor (d8 + %platform%-tick-processor friend)
JavaScript
322
star
6

dbus-native

D-bus protocol client and server for node.js written in native javascript
JavaScript
259
star
7

crconsole

Remote JavaScript console for Chrome/Webkit
JavaScript
254
star
8

nodejs-mysql-native

Native mysql async client for node.js
JavaScript
239
star
9

react-x11

React renderer with X11 as a target
JavaScript
233
star
10

node-rfb2

rfb wire protocol client and server
JavaScript
135
star
11

crmux

Chrome developer tools remote protocol multiplexer.
JavaScript
123
star
12

ntk

node.js desktop UI toolkit
JavaScript
91
star
13

node-wrk

wrk load testing tool node wrapper
JavaScript
80
star
14

hot-module-replacement

Hot module replacement for node.js
JavaScript
56
star
15

pugify

jade transform for browserify v2. Sourcemaps generation included.
JavaScript
41
star
16

node-adbhost

node.js adb (android debug bridge) client
JavaScript
41
star
17

mysql-pg-proxy

mysql to postgres proxy server
JavaScript
34
star
18

yandex-translate

Yandex.Translate translation service client
JavaScript
31
star
19

osquery-node

node.js client for osquery
JavaScript
31
star
20

node-i3

i3-ipc node.js client
JavaScript
31
star
21

mysqlite.js

sqlite db server talking mysql protocol, all native js
JavaScript
30
star
22

node-vnc

Node.js vnc client with gui
JavaScript
15
star
23

mysql-co

mysql2 wrappers for "co"
JavaScript
15
star
24

ni

script to simplify node-inspector debugger workflow
JavaScript
14
star
25

mysql-osquery-proxy

mysql server proxying queries to facebook osquery daemon
JavaScript
14
star
26

node-shaper

Create through stream which limits speed to bytes per second/chunks per second
JavaScript
13
star
27

npdf

desktop pdf viewer using pdfium.js + node-x11
JavaScript
12
star
28

nierika

pixel based testing library with VNC as a driver
JavaScript
12
star
29

node-ptv

Public Transport Victoria API client for node.js
JavaScript
12
star
30

dbusfs

FUSE filesystem exposing dbus objects
JavaScript
11
star
31

rfbrecord

stream VNC connection to a video file
JavaScript
11
star
32

ansi-vnc

terminal vnc client
JavaScript
10
star
33

atom-vnc

VNC client for atom editor
CoffeeScript
9
star
34

node-pidgin

Pidgin node.js client using pidgin dbus api
JavaScript
7
star
35

react-show-in-atom

Navigate to line of code where react element is defined by clicking on it
JavaScript
6
star
36

node-skype-dbus

node.js SkypeAPI dbus client
JavaScript
6
star
37

node-cli-debugger

node.js command-line debugger
JavaScript
5
star
38

nodejs-memcached-native

Native async memcached client for node.js
5
star
39

exec-stream

create read-write stream from child process stdin/stdout
JavaScript
5
star
40

node-gday

dns-sd client (Avahi/dbus wrapper)
JavaScript
5
star
41

repl-co

node repl with yield support
JavaScript
5
star
42

v8-debugger-protocol

v8 debugger protocol client
JavaScript
5
star
43

node-skype

node.js SkypeAPI client
JavaScript
4
star
44

node-dbusmenu

node.js dbusmenu client
JavaScript
3
star
45

x11-xsettings

XSETTINGS binary format encoder/decoder
JavaScript
3
star
46

embed-source-map

Convert sourcemaps with external references to inlineable sourcemap
JavaScript
3
star
47

gaussian-convolution-kernel

calculate square matrix - gaussian blur convolution kernel
JavaScript
3
star
48

tfn

JavaScript
3
star
49

node-harfbuzz

node.js harfbuzz bindings
C++
3
star
50

node-resolve-cache

Cache and reuse results of node module file name resolution algorithm
JavaScript
3
star
51

_sidorares.github.com

personal tech blog
CSS
2
star
52

melbnodejs

Melbourne node.js meetup - proposals, links, website
2
star
53

xclimsg

send ewmh ClientMessage to x11 window from command line
JavaScript
2
star
54

australian-business-number

validate ABN
JavaScript
2
star
55

pr-linecommits

Chrome extension to help reviw "files" pane of github PR page
JavaScript
2
star
56

xml2jade

xml -> jade convertor
JavaScript
2
star
57

diamond

stdin + arguments composite stream (aka <> or diamond)
JavaScript
2
star
58

canvas-fontstyle

canvas fontStyle parser
JavaScript
1
star
59

netlify-test

HTML
1
star
60

Browserless

Dockerfile
1
star
61

node-streamagent

Connect http/websockets node.js client using arbitrary duplex stream
JavaScript
1
star
62

australian-tax-rate

return tax rate based on annual income
JavaScript
1
star
63

webpubsub-local

A drop in replacement for Azure webpubsub you can run locally
JavaScript
1
star
64

node-mssql

Node.js support for talking to microsoft sql server. [currently only connect is OK]
JavaScript
1
star
65

hackduino

arduino workshop examples
1
star
66

node-unpack

Pack and unpack binary data using pyhon-alike pack syntax
JavaScript
1
star
67

node-skype-applescript

skype applescript wrapper + repl
1
star
68

mfe-version-resolver

JavaScript
1
star
69

d3bench

benchmark app
JavaScript
1
star
70

logcomments

wrap every comments in JavaScript source to function call
JavaScript
1
star
71

android-xserver

This is a fork of Matt Kwan's android X server project
Java
1
star
72

http-nodejs

JavaScript
1
star
73

compare-energy-rates

graph cost of your electricyty based on your past usage and new rates
1
star
74

mysql-client-benchmarks

JavaScript
1
star
75

andreysidorov.com

HTML
1
star
76

argnames

print javascript function argument values together with names from function definition
JavaScript
1
star
77

generators-and-co

My presentation at MelbJS about generators & generator control flow libraries
JavaScript
1
star