[![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Linux Build][travis-image]][travis-url] [![Windows Build][appveyor-image]][appveyor-url] [![Test Coverage][coveralls-image]][coveralls-url]
This is a Node.js module available through the npm registry.
Before installing, download and install Node.js. Node.js 0.6 or higher is required.
Installation is done using the
npm install command:
$ 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 mysqljs/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 (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
From this example, you can learn the following:
end() which makes sure all remaining
queries are executed before sending a quit packet to the mysql server.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:
The following companies have supported this project financially, allowing me to spend more time on it (ordered by time of contribution):
If you'd like to discuss this module, or ask questions about it, please use one of the following:
mysql)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 (error, results, fields) {
if (error) throw error;
// connected!
});
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.
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 configured on the MySQL server. This is used to type cast server date/time values to JavaScript Date object and vice versa. This can be 'local', 'Z', or an offset in the form +HH:MM or -HH:MM. (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 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] (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 if supportBigNumbers is disabled.dateStrings: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather than
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)trace: Generates stack traces on Error to include call site of library
entrance ("long stack traces"). Slight performance penalty for most calls.
(Default: true)localInfile: Allow LOAD DATA INFILE to use the LOCAL modifier. (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, check
Connection 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.
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.pemWhen connecting to other servers, you will need to provide an object of options, in the same format as tls.createSecureContext. 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
}
});
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).
var connection = mysql.createConnection({
// disable FOUND_ROWS flag, enable IGNORE_SPACE flag
flags: '-FOUND_ROWS,IGNORE_SPACE'
});
The following flags are available:
COMPRESS - Enable protocol compression. This feature is not currently supported
by the Node.js implementation so cannot be turned on. (Default off)CONNECT_WITH_DB - Ability to specify the database on connection. (Default on)FOUND_ROWS - Send the found rows instead of the affected rows as affectedRows.
(Default on)IGNORE_SIGPIPE - Don't issue SIGPIPE if network failures. This flag has no effect
on this Node.js implementation. (Default on)IGNORE_SPACE - Let the parser ignore spaces before the ( in queries. (Default on)INTERACTIVE - Indicates to the MySQL server this is an "interactive" client. This
will use the interactive timeouts on the MySQL server and report as interactive in
the process list. (Default off)LOCAL_FILES - Can use LOAD DATA LOCAL. This flag is controlled by the connection
option localInfile. (Default on)LONG_FLAG - Longer flags in Protocol::ColumnDefinition320. (Default on)LONG_PASSWORD - Use the improved version of Old Password Authentication.
(Default on)MULTI_RESULTS - Can handle multiple resultsets for queries. (Default on)MULTI_STATEMENTS - The client may send multiple statement per query or
statement prepare (separated by ;). This flag is controlled by the connection
option multipleStatements. (Default off)NO_SCHEMAODBC Special handling of ODBC behaviour. This flag has no effect on this Node.js
implementation. (Default on)PLUGIN_AUTH - Uses the plugin authentication mechanism when connecting to the
MySQL server. This feature is not currently supported by the Node.js implementation
so cannot be turned on. (Default off)PROTOCOL_41 - Uses the 4.1 protocol.$ claude mcp add mysql \
-- python -m otcore.mcp_server <graph>