[关闭]
@fzbing 2016-07-14T11:02:20.000000Z 字数 34686 阅读 1172

nodejs mysql 手册

未分类


mysql

NPM Version
NPM Downloads
Node.js Version
master.svg?label=linux未知大小
master.svg?label=windows未知大小
Test Coverage

Table of Contents

Install

  1. $ 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:

  1. $ npm install mysqljs/mysql

Introduction

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:

  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection({
  3. host : 'localhost',
  4. user : 'me',
  5. password : 'secret',
  6. database : 'my_db'
  7. });
  8. connection.connect();
  9. connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  10. if (err) throw err;
  11. console.log('The solution is: ', rows[0].solution);
  12. });
  13. connection.end();

From this example, you can learn the following:

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:

Sponsors

The following companies have supported this project financially, allowing me to
spend more time on it (ordered by time of contribution):

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:

Establishing connections

The recommended way to establish a connection is this:

  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection({
  3. host : 'example.org',
  4. user : 'bob',
  5. password : 'secret'
  6. });
  7. connection.connect(function(err) {
  8. if (err) {
  9. console.error('error connecting: ' + err.stack);
  10. return;
  11. }
  12. console.log('connected as id ' + connection.threadId);
  13. });

However, a connection can also be implicitly established by invoking a query:

  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection(...);
  3. connection.query('SELECT 1', function(err, rows) {
  4. // connected! (unless `err` is set)
  5. });

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:

In addition to passing these options as an object, you can also use a url
string. For example:

  1. 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:

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:

  1. var connection = mysql.createConnection({
  2. host : 'localhost',
  3. ssl : {
  4. ca : fs.readFileSync(__dirname + '/mysql-ca.crt')
  5. }
  6. });

You can also connect to a MySQL server without properly providing the appropriate
CA to trust. You should not do this.

  1. var connection = mysql.createConnection({
  2. host : 'localhost',
  3. ssl : {
  4. // DO NOT DO THIS
  5. // set up your ca correctly to trust the connection
  6. rejectUnauthorized: false
  7. }
  8. });

Terminating connections

There are two ways to end a connection. Terminating a connection gracefully is
done by calling the end() method:

  1. connection.end(function(err) {
  2. // The connection is terminated now
  3. });

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.

  1. connection.destroy();

Unlike end() the destroy() method does not take a callback argument.

Pooling connections

Use pool directly.

  1. var mysql = require('mysql');
  2. var pool = mysql.createPool({
  3. connectionLimit : 10,
  4. host : 'example.org',
  5. user : 'bob',
  6. password : 'secret',
  7. database : 'my_db'
  8. });
  9. pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
  10. if (err) throw err;
  11. console.log('The solution is: ', rows[0].solution);
  12. });

Connections can be pooled to ease sharing a single connection, or managing
multiple connections.

  1. var mysql = require('mysql');
  2. var pool = mysql.createPool({
  3. host : 'example.org',
  4. user : 'bob',
  5. password : 'secret',
  6. database : 'my_db'
  7. });
  8. pool.getConnection(function(err, connection) {
  9. // connected! (unless `err` is set)
  10. });

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.

  1. var mysql = require('mysql');
  2. var pool = mysql.createPool(...);
  3. pool.getConnection(function(err, connection) {
  4. // Use the connection
  5. connection.query( 'SELECT something FROM sometable', function(err, rows) {
  6. // And done with the connection.
  7. connection.release();
  8. // Don't use the connection here, it has been returned to the pool.
  9. });
  10. });

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:

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.

  1. pool.on('connection', function (connection) {
  2. connection.query('SET SESSION auto_increment_increment=1')
  3. });

enqueue

The pool will emit an enqueue event when a callback has been queued to wait for
an available connection.

  1. pool.on('enqueue', function () {
  2. console.log('Waiting for available connection slot');
  3. });

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:

  1. pool.end(function (err) {
  2. // all connections in the pool have ended
  3. });

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

PoolCluster provides multiple hosts connection. (group & retry & selector)

  1. // create
  2. var poolCluster = mysql.createPoolCluster();
  3. // add configurations (the config is a pool config object)
  4. poolCluster.add(config); // add configuration with automatic name
  5. poolCluster.add('MASTER', masterConfig); // add a named configuration
  6. poolCluster.add('SLAVE1', slave1Config);
  7. poolCluster.add('SLAVE2', slave2Config);
  8. // remove configurations
  9. poolCluster.remove('SLAVE2'); // By nodeId
  10. poolCluster.remove('SLAVE*'); // By target group : SLAVE1-2
  11. // Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
  12. poolCluster.getConnection(function (err, connection) {});
  13. // Target Group : MASTER, Selector : round-robin
  14. poolCluster.getConnection('MASTER', function (err, connection) {});
  15. // Target Group : SLAVE1-2, Selector : order
  16. // If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)
  17. poolCluster.on('remove', function (nodeId) {
  18. console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1
  19. });
  20. poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {});
  21. // of namespace : of(pattern, selector)
  22. poolCluster.of('*').getConnection(function (err, connection) {});
  23. var pool = poolCluster.of('SLAVE*', 'RANDOM');
  24. pool.getConnection(function (err, connection) {});
  25. pool.getConnection(function (err, connection) {});
  26. // close all connections
  27. poolCluster.end(function (err) {
  28. // all connections in the pool cluster have ended
  29. });

PoolCluster options

  1. var clusterConfig = {
  2. removeNodeErrorCount: 1, // Remove the node immediately when connection fails.
  3. defaultSelector: 'ORDER'
  4. };
  5. var poolCluster = mysql.createPoolCluster(clusterConfig);

Switching users and altering connection state

MySQL offers a changeUser command that allows you to alter the current user and
other aspects of the connection without shutting down the underlying socket:

  1. connection.changeUser({user : 'john'}, function(err) {
  2. if (err) throw err;
  3. });

The available options for this feature are:

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 or Pool instance).

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

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

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

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

The third form .query(options, callback) comes when using various advanced
options on the query, like escaping query values,
joins with overlapping column names,
timeouts, and type casting.

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

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.

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

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:

  1. var userId = 'some user provided value';
  2. var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
  3. connection.query(sql, function(err, results) {
  4. // ...
  5. });

Alternatively, you can use ? characters as placeholders for values you would
like to have escaped like this:

  1. connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
  2. // ...
  3. });

Multiple placeholders are mapped to values in the same order as passed. For example,
in the following query foo equals a, bar equals b, baz equals c, and
id will be userId:

  1. connection.query('UPDATE users SET foo = ?, bar = ?, baz = ? WHERE id = ?', ['a', 'b', 'c', userId], function(err, results) {
  2. // ...
  3. });

This looks similar to prepared statements in MySQL, however it really just uses
the same connection.escape() method internally.

Caution This also differs from prepared statements in that all ? are
replaced, even those contained in comments and strings.

Different value types are escaped differently, here is how:

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

  1. var post = {id: 1, title: 'Hello MySQL'};
  2. var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  3. // Neat!
  4. });
  5. console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'

If you feel the need to escape queries by yourself, you can also use the escaping
function directly:

  1. var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL");
  2. console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL'

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:

  1. var sorter = 'date';
  2. var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);
  3. connection.query(sql, function(err, results) {
  4. // ...
  5. });

It also supports adding qualified identifiers. It will escape both parts.

  1. var sorter = 'date';
  2. var sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter);
  3. connection.query(sql, function(err, results) {
  4. // ...
  5. });

Alternatively, you can use ?? characters as placeholders for identifiers you would
like to have escaped like this:

  1. var userId = 1;
  2. var columns = ['username', 'email'];
  3. var query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function(err, results) {
  4. // ...
  5. });
  6. console.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1

Please note that this last character sequence is experimental and syntax might change

When you pass an Object to .escape() or .query(), .escapeId() is used to avoid SQL injection in object keys.

Preparing Queries

You can use mysql.format to prepare a query with multiple insertion points, utilizing the proper escaping for ids and values. A simple example of this follows:

  1. var sql = "SELECT * FROM ?? WHERE ?? = ?";
  2. var inserts = ['users', 'id', userId];
  3. sql = mysql.format(sql, inserts);

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.

Here's an example of how to implement another format:

  1. connection.config.queryFormat = function (query, values) {
  2. if (!values) return query;
  3. return query.replace(/\:(\w+)/g, function (txt, key) {
  4. if (values.hasOwnProperty(key)) {
  5. return this.escape(values[key]);
  6. }
  7. return txt;
  8. }.bind(this));
  9. };
  10. connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });

Getting the id of an inserted row

If you are inserting a row into a table with an auto increment primary key, you
can retrieve the insert id like this:

  1. connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {
  2. if (err) throw err;
  3. console.log(result.insertId);
  4. });

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.

  1. connection.query('DELETE FROM posts WHERE title = "wrong"', function (err, result) {
  2. if (err) throw err;
  3. console.log('deleted ' + result.affectedRows + ' rows');
  4. })

Getting the number of changed rows

You can get the number of changed rows from an update statement.

"changedRows" differs from "affectedRows" in that it does not count updated rows
whose values were not changed.

  1. connection.query('UPDATE posts SET ...', function (err, result) {
  2. if (err) throw err;
  3. console.log('changed ' + result.changedRows + ' rows');
  4. })

Getting the connection ID

You can get the MySQL connection ID ("thread ID") of a given connection using the threadId
property.

  1. connection.connect(function(err) {
  2. if (err) throw err;
  3. console.log('connected as id ' + connection.threadId);
  4. });

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:

  1. var query = connection.query('SELECT * FROM posts');
  2. query
  3. .on('error', function(err) {
  4. // Handle error, an 'end' event will be emitted after this as well
  5. })
  6. .on('fields', function(fields) {
  7. // the field packets for the rows to follow
  8. })
  9. .on('result', function(row) {
  10. // Pausing the connnection is useful if your processing involves I/O
  11. connection.pause();
  12. processRow(row, function() {
  13. connection.resume();
  14. });
  15. })
  16. .on('end', function() {
  17. // all rows have been received
  18. });

Please note a few things about the example above:

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 Readable
Streams2 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:

  1. connection.query('SELECT * FROM posts')
  2. .stream({highWaterMark: 5})
  3. .pipe(...);

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:

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

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

  1. connection.query('SELECT 1; SELECT 2', function(err, results) {
  2. if (err) throw err;
  3. // `results` is an array with one element for every statement in the query:
  4. console.log(results[0]); // [{1: 1}]
  5. console.log(results[1]); // [{2: 2}]
  6. });

Additionally you can also stream the results of multiple statement queries:

  1. var query = connection.query('SELECT 1; SELECT 2');
  2. query
  3. .on('fields', function(fields, index) {
  4. // the fields for the result rows that follow
  5. })
  6. .on('result', function(row, index) {
  7. // index refers to the statement this result belongs to (starts at 0)
  8. });

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:

  1. var options = {sql: '...', nestTables: true};
  2. connection.query(options, function(err, results) {
  3. /* results will be an array like this now:
  4. [{
  5. table1: {
  6. fieldA: '...',
  7. fieldB: '...',
  8. },
  9. table2: {
  10. fieldA: '...',
  11. fieldB: '...',
  12. },
  13. }, ...]
  14. */
  15. });

Or use a string separator to have your results merged.

  1. var options = {sql: '...', nestTables: '_'};
  2. connection.query(options, function(err, results) {
  3. /* results will be an array like this now:
  4. [{
  5. table1_fieldA: '...',
  6. table1_fieldB: '...',
  7. table2_fieldA: '...',
  8. table2_fieldB: '...',
  9. }, ...]
  10. */
  11. });

Transactions

Simple transaction support is available at the connection level:

  1. connection.beginTransaction(function(err) {
  2. if (err) { throw err; }
  3. connection.query('INSERT INTO posts SET title=?', title, function(err, result) {
  4. if (err) {
  5. return connection.rollback(function() {
  6. throw err;
  7. });
  8. }
  9. var log = 'Post ' + result.insertId + ' added';
  10. connection.query('INSERT INTO log SET data=?', log, function(err, result) {
  11. if (err) {
  12. return connection.rollback(function() {
  13. throw err;
  14. });
  15. }
  16. connection.commit(function(err) {
  17. if (err) {
  18. return connection.rollback(function() {
  19. throw err;
  20. });
  21. }
  22. console.log('success!');
  23. });
  24. });
  25. });
  26. });

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.

  1. connection.ping(function (err) {
  2. if (err) throw err;
  3. console.log('Server responded to ping');
  4. })

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.

  1. // Kill query after 60s
  2. connection.query({sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000}, function (err, rows) {
  3. if (err && err.code === 'PROTOCOL_SEQUENCE_TIMEOUT') {
  4. throw new Error('too long to count table rows!');
  5. }
  6. if (err) {
  7. throw err;
  8. }
  9. console.log(rows[0].count + ' rows');
  10. });

Error handling

This module comes with a consistent approach to error handling that you should
review carefully in order to write solid applications.

Most errors created by this module are instances of the JavaScript Error
object. Additionally they typically come with two extra properties:

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:

  1. var connection = require('mysql').createConnection({
  2. port: 84943, // WRONG PORT
  3. });
  4. connection.connect(function(err) {
  5. console.log(err.code); // 'ECONNREFUSED'
  6. console.log(err.fatal); // true
  7. });
  8. connection.query('SELECT 1', function(err) {
  9. console.log(err.code); // 'ECONNREFUSED'
  10. console.log(err.fatal); // true
  11. });

Normal errors however are only delegated to the callback they belong to. So in
the example below, only the first callback receives an error, the second query
works as expected:

  1. connection.query('USE name_of_db_that_does_not_exist', function(err, rows) {
  2. console.log(err.code); // 'ER_BAD_DB_ERROR'
  3. });
  4. connection.query('SELECT 1', function(err, rows) {
  5. console.log(err); // null
  6. console.log(rows.length); // 1
  7. });

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:

  1. connection.on('error', function(err) {
  2. console.log(err.code); // 'ER_BAD_DB_ERROR'
  3. });
  4. connection.query('USE name_of_db_that_does_not_exist');

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:

  1. // I am Chuck Norris:
  2. 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

Date

Buffer

String

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

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:

  1. var connection = require('mysql').createConnection({typeCast: false});

Or on the query level:

  1. var options = {sql: '...', typeCast: false};
  2. var query = connection.query(options, function(err, results) {
  3. });

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:

  1. connection.query({
  2. sql: '...',
  3. typeCast: function (field, next) {
  4. if (field.type == 'TINY' && field.length == 1) {
  5. return (field.string() == '1'); // 1 = true, 0 = false
  6. }
  7. return next();
  8. }
  9. });

WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. (see #539 for discussion)

  1. field.string()
  2. field.buffer()
  3. field.geometry()

are aliases for

  1. parser.parseLengthCodedString()
  2. parser.parseLengthCodedBuffer()
  3. parser.parseGeometryValue()

You can find which field function you need to use by looking at: RowDataPacket.prototype._typeCast

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.

  1. var connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS");

Default Flags

The following flags are sent by default on a new connection:

In addition, the following flag will be sent if the option multipleStatements
is set to true:

Other Available Flags

There are other flags available. They may or may not function, but are still
available to specify.

Debugging and reporting problems

If you are running into problems, one thing that may help is enabling the
debug mode for the connection:

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

This will print all incoming and outgoing packets on stdout. You can also restrict debugging to
packet types by passing an array of types to debug:

  1. var connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']});

to restrict debugging to the query and data packets.

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

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

  1. $ 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:

  1. $ mysql -u root -e "CREATE DATABASE IF NOT EXISTS node_mysql_test"
  2. $ MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_DATABASE=node_mysql_test MYSQL_USER=root MYSQL_PASSWORD= FILTER=integration npm test

Todo

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注