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 used host
and port are 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 (like utf8_general_ci). If a SQL-level charset is specified (like utf8mb4)
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)

supportBigNumbers: When dealing with big numbers (BIGINT and DECIMAL columns) in the database,
you should enable this option (Default: false).

bigNumberStrings: Enabling both supportBigNumbers and bigNumberStrings forces big numbers
(BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: false).
Enabling supportBigNumbers but leaving bigNumberStrings disabled 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 if supportBigNumbers is disabled.

dateStrings: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then
inflated into JavaScript Date objects. Can be true/false or an array of type names to keep as
strings. (Default: false)

debug: Prints protocol details to stdout. Can be true/false or an array of packet type names
that should be printed. (Default: false)

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:

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 the
COM_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

Rather than creating and managing connections one-by-one, this module also
provides built-in connection pooling using mysql.createPool(config).
Read more about connection pooling.

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 connectionconnection.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 packet is sent
to the server to check if the connection is still good.

Pool options

Pools accept all the same options as a connection.
When creating a new connection, the options are simply passed to the connection
constructor. In addition to those options pools accept a few extras:

acquireTimeout: The milliseconds before a timeout occurs during the connection
acquisition. This is slightly different from connectTimeout, 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. If true, the pool will queue the
connection request and call it when one becomes available. If false, 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 from getConnection. If set to 0, 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.

enqueue

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

PoolCluster options

canRetry: If true, PoolCluster will attempt to reconnect when connection fails. (Default: true)

removeNodeErrorCount: If connection fails, node's errorCount increases.
When errorCount is greater than removeNodeErrorCount, remove a node in the PoolCluster. (Default: 5)

restoreNodeTimeout: If connection fails, specifies the number of milliseconds
before another connection attempt will be made. If set to 0, then node will be
removed instead and never re-used. (Default: 0)

password: The password of the new user (defaults to the previous one).

charset: The new charset (defaults to the previous one).

database: The new database (defaults to the previous one).

A sometimes useful side effect of this functionality is that this function also
resets any connection state (variables, transactions, etc.).

Errors encountered during this operation are treated as fatal connection errors
by this module.

Server disconnects

You may lose the connection to a MySQL server due to network problems, the
server timing you out, the server being restarted, or crashing. All of these
events are considered fatal errors, and will have the err.code =
'PROTOCOL_CONNECTION_LOST'. See the Error Handling section
for more information.

Re-connecting a connection is done by establishing a new connection. Once
terminated, an existing connection object cannot be re-connected by design.

With Pool, disconnected connections will be removed from the pool freeing up
space for a new connection to be created on the next getConnection call.

Performing queries

The most basic way to perform a query is to call the .query() method on an object
(like a Connection, Pool, or PoolNamespace instance).

The simplest form of .query() is .query(sqlString, callback), where a SQL string
is the first argument and the second is a callback:

connection.query('SELECT * FROM `books` WHERE `author` = "David"', function (error, results, fields) {
// error will be an Error if one occurred during the query// results will contain the results of the query// fields will contain information about the returned results fields (if any)
});

The second form .query(sqlString, values, callback) comes when using
placeholder values (see escaping query values):

connection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
// error will be an Error if one occurred during the query// results will contain the results of the query// fields will contain information about the returned results fields (if any)
});

connection.query({
sql:'SELECT * FROM `books` WHERE `author` = ?',
timeout:40000, // 40s
values: ['David']
}, function (error, results, fields) {
// error will be an Error if one occurred during the query// results will contain the results of the query// fields will contain information about the returned results fields (if any)
});

Note that a combination of the second and third forms can be used where the
placeholder values are passes as an argument and not in the options object.
The values argument will override the values in the option object.

connection.query({
sql:'SELECT * FROM `books` WHERE `author` = ?',
timeout:40000, // 40s
},
['David'],
function (error, results, fields) {
// error will be an Error if one occurred during the query// results will contain the results of the query// fields will contain information about the returned results fields (if any)
}
);

Escaping query values

In order to avoid SQL Injection attacks, you should always escape any user
provided data before using it inside a SQL query. You can do so using the
mysql.escape(), connection.escape() or pool.escape() methods:

Objects are turned into key = 'val' pairs for each enumerable property on
the object. If the property's value is a function, it is skipped; if the
property's value is an object, toString() is called on it and the returned
value is used.

undefined / null are converted to NULL

NaN / Infinity are left as-is. MySQL does not support these, and trying
to insert them as values will trigger MySQL errors until they implement
support.

If you paid attention, you may have noticed that this escaping allows you
to do neat things like this:

Escaping query identifiers

If you can't trust an SQL identifier (database / table / column name) because it is
provided by a user, you should escape it with mysql.escapeId(identifier),
connection.escapeId(identifier) or pool.escapeId(identifier) like this:

Following this you then have a valid, escaped query that you can then send to the database safely. This is useful if you are looking to prepare the query before actually sending it to the database. As mysql.format is exposed from SqlString.format you also have the option (but are not required) to pass in stringifyObject and timezone, allowing you provide a custom means of turning objects into strings, as well as a location-specific/timezone-aware Date.

Custom format

If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in .escape() or any other connection function.

When dealing with big numbers (above JavaScript Number precision limit), you should
consider enabling supportBigNumbers option to be able to read the insert id as a
string, otherwise it will throw an error.

This option is also required when fetching big numbers from the database, otherwise
you will get values rounded to hundreds or thousands due to the precision limit.

Getting the number of affected rows

You can get the number of affected rows from an insert, update or delete statement.

Executing queries in parallel

The MySQL protocol is sequential, this means that you need multiple connections
to execute queries in parallel. You can use a Pool to manage connections, one
simple approach is to create one connection per incoming http request.

Streaming query rows

Sometimes you may want to select large quantities of rows and process each of
them as they are received. This can be done like this:

Usually you will want to receive a certain amount of rows before starting to
throttle the connection using pause(). This number will depend on the
amount and size of your rows.

pause() / resume() operate on the underlying socket and parser. You are
guaranteed that no more 'result' events will fire after calling pause().

You MUST NOT provide a callback to the query() method when streaming rows.

The 'result' event will fire for both rows as well as OK packets
confirming the success of a INSERT/UPDATE query.

It is very important not to leave the result paused too long, or you may
encounter Error: Connection lost: The server closed the connection.
The time limit for this is determined by the
net_write_timeout setting
on your MySQL server.

Additionally you may be interested to know that it is currently not possible to
stream individual row columns, they will always be buffered up entirely. If you
have a good use case for streaming large fields to and from MySQL, I'd love to
get your thoughts and contributions on this.

Piping results with Streams2

The query object provides a convenience method .stream([options]) that wraps
query events into a ReadableStreams2 object. This
stream can easily be piped downstream and provides automatic pause/resume,
based on downstream congestion and the optional highWaterMark. The
objectMode parameter of the stream is set to true and cannot be changed
(if you need a byte stream, you will need to use a transform stream, like
objstream for example).

For example, piping query results into another stream (with a max buffer of 5
objects) is simply:

Multiple statement queries

Support for multiple statements is disabled for security reasons (it allows for
SQL injection attacks if values are not properly escaped). To use this feature
you have to enable it for your connection:

var connection =mysql.createConnection({multipleStatements:true});

Once enabled, you can execute multiple statement queries like any other query:

If one of the statements in your query causes an error, the resulting Error
object contains a err.index property which tells you which statement caused
it. MySQL will also stop executing any remaining statements when an error
occurs.

Please note that the interface for streaming multiple statement queries is
experimental and I am looking forward to feedback on it.

Stored procedures

You can call stored procedures from your queries as with any other mysql driver.
If the stored procedure produces several result sets, they are exposed to you
the same way as the results for multiple statement queries.

Joins with overlapping column names

When executing joins, you are likely to get result sets with overlapping column
names.

By default, node-mysql will overwrite colliding column names in the
order the columns are received from MySQL, causing some of the received values
to be unavailable.

However, you can also specify that you want your columns to be nested below
the table name like this:

Please note that beginTransaction(), commit() and rollback() are simply convenience
functions that execute the START TRANSACTION, COMMIT, and ROLLBACK commands respectively.
It is important to understand that many commands in MySQL can cause an implicit commit,
as described in the MySQL documentation

Ping

A ping packet can be sent over a connection using the connection.ping method. This
method will send a ping packet to the server and when the server responds, the callback
will fire. If an error occurred, the callback will fire with an error argument.

Timeouts

Every operation takes an optional inactivity timeout option. This allows you to
specify appropriate timeouts for operations. It is important to note that these
timeouts are not part of the MySQL protocol, and rather timeout operations through
the client. This means that when a timeout is reached, the connection it occurred
on will be destroyed and no further operations can be performed.

err.fatal: Boolean, indicating if this error is terminal to the connection
object. If the error is not from a MySQL protocol operation, this properly
will not be defined.

Fatal errors are propagated to all pending callbacks. In the example below, a
fatal error is triggered by trying to connect to an invalid port. Therefore the
error object is propagated to both pending callbacks:

Last but not least: If a fatal errors occurs and there are no pending
callbacks, or a normal error occurs which has no callback belonging to it, the
error is emitted as an 'error' event on the connection object. This is
demonstrated in the example below:

Note: 'error' events are special in node. If they occur without an attached
listener, a stack trace is printed and your process is killed.

tl;dr: This module does not want you to deal with silent failures. You
should always provide callbacks to your method calls. If you want to ignore
this advice and suppress unhandled errors, you can do this:

// I am Chuck Norris:connection.on('error', function() {});

Exception Safety

This module is exception safe. That means you can continue to use it, even if
one of your callback functions throws an error which you're catching using
'uncaughtException' or a domain.

Type casting

For your convenience, this driver will cast mysql types into native JavaScript
types by default. The following mappings exist:

Number

TINYINT

SMALLINT

INT

MEDIUMINT

YEAR

FLOAT

DOUBLE

Date

TIMESTAMP

DATE

DATETIME

Buffer

TINYBLOB

MEDIUMBLOB

LONGBLOB

BLOB

BINARY

VARBINARY

BIT (last byte will be filled with 0 bits as necessary)

String

Note text in the binary character set is returned as Buffer, rather
than a string.

CHAR

VARCHAR

TINYTEXT

MEDIUMTEXT

LONGTEXT

TEXT

ENUM

SET

DECIMAL (may exceed float precision)

BIGINT (may exceed float precision)

TIME (could be mapped to Date, but what date would be set?)

GEOMETRY (never used those, get in touch if you do)

It is not recommended (and may go away / change in the future) to disable type
casting, but you can currently do so on either the connection:

You can also pass a function and handle type casting yourself. You're given some
column information like database, table and name and also type and length. If you
just want to apply a custom type casting to a specific type you can do it and then
fallback to the default. Here's an example of converting TINYINT(1) to boolean:

Connection Flags

If, for any reason, you would like to change the default connection flags, you
can use the connection option flags. Pass a string with a comma separated list
of items to add to the default flags. If you don't want a default flag to be used
prepend the flag with a minus sign. To add a flag that is not in the default list,
just write the flag name, or prefix it with a plus (case insensitive).

Please note that some available flags that are not supported (e.g.: Compression),
are still not allowed to be specified.

Example

The next example blacklists FOUND_ROWS flag from default connection flags.

If that does not help, feel free to open a GitHub issue. A good GitHub issue
will have:

The minimal amount of code required to reproduce the problem (if possible)

As much debugging output and information about your environment (mysql
version, node version, os, etc.) as you can gather.

Contributing

This project welcomes contributions from the community. Contributions are
accepted using GitHub pull requests. If you're not familiar with making
GitHub pull requests, please refer to the
GitHub documentation "Creating a pull request".

For a good pull request, we ask you provide the following:

Try to include a clear description of your pull request in the description.
It should include the basic "what" and "why"s for the request.

The tests should pass as best as you can. See the Running tests
section on hwo to run the different tests. GitHub will automatically run
the tests as well, to act as a safety net.

The pull request should include tests for the change. A new feature should
have tests for the new feature and bug fixes should include a test that fails
without the corresponding code change and passes after they are applied.
The command npm run test-cov will generate a coverage/ folder that
contains HTML pages of the code coverage, to better understand if everything
you're adding is being tested.

If the pull request is a new feature, please be sure to include all
appropriate documentation additions in the Readme.md file as well.

To help ensure that your code is similar in style to the existing code,
run the command npm run lint and fix any displayed issues.

Running tests

The test suite is split into two parts: unit tests and integration tests.
The unit tests run on any machine while the integration tests require a
MySQL server instance to be setup.

Running unit tests

$ FILTER=unit npm test

Running integration tests

Set the environment variables MYSQL_DATABASE, MYSQL_HOST, MYSQL_PORT,
MYSQL_USER and MYSQL_PASSWORD. MYSQL_SOCKET can also be used in place
of MYSQL_HOST and MYSQL_PORT to connect over a UNIX socket. Then run
npm test.

For example, if you have an installation of mysql running on localhost:3306
and no password set for the root user, run: