Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
M

mysql

> 数据库
Open source

A pure node.js JavaScript Client implementing the MySQL protocol.

18.6K stars0 likes5 views
WebsiteGitHub

About

A pure node.js JavaScript Client implementing the MySQL protocol.

mysql

[![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-image]][node-url] [![Linux Build][github-actions-ci-image]][github-actions-ci-url] [![Windows Build][appveyor-image]][appveyor-url] [![Test Coverage][coveralls-image]][coveralls-url]

Table of Contents

  • Install
  • Introduction
  • Contributors
  • Sponsors
  • Community
  • Establishing connections
  • Connection options
    • SSL options
    • Connection flags
  • Terminating connections
  • Pooling connections
  • Pool options
  • Pool events
    • acquire
    • connection
    • enqueue
    • release
  • Closing all the connections in a pool
  • PoolCluster
    • PoolCluster options
  • Switching users and altering connection state
  • Server disconnects
  • Performing queries
  • Escaping query values
  • Escaping query identifiers
    • Preparing Queries
    • Custom format
  • Getting the id of an inserted row
  • Getting the number of affected rows
  • Getting the number of changed rows
  • Getting the connection ID
  • Executing queries in parallel
  • Streaming query rows
    • Piping results with Streams
  • Multiple statement queries
  • Stored procedures
  • Joins with overlapping column names
  • Transactions
  • Ping
  • Timeouts
  • Error handling
  • Exception Safety
  • Type casting
    • Number
    • Date
    • Buffer
    • String
    • Custom type casting
  • Debugging and reporting problems
  • Security issues
  • Contributing
  • Running tests
    • Running unit tests
    • Running integration tests
  • Todo

Install

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:

bash
$ 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:

bash
$ 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:

javascript
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:

  • Every method you invoke on a connection is queued and executed in sequence.
  • Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

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:

  • Andrey Hristov (Oracle) - for helping me with protocol questions.
  • Ulf Wendel (Oracle) - for helping me with protocol questions.

Sponsors

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

  • Transloadit (my startup, we do file uploading & video encoding as a service, check it out)
  • Joyent
  • pinkbike.com
  • Holiday Extras (they are hiring)
  • Newscope (they are hiring)

Community

If you'd like to discuss this module, or ask questions about it, please use one of the following:

  • Mailing list: https://groups.google.com/forum/#!forum/node-mysql
  • IRC Channel: #node.js (on freenode.net, I pay attention to any message including the term mysql)

Establishing connections

The recommended way to establish a connection is this:

javascript
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:

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

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 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. (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] (https://tc39.es/ecma262/#sec-ecmascript-language-types-number-type) (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:

javascript
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:

  • "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.pem

When connecting to other servers, you will need to provide an object with any of the following options:

  • ca: The certificate(s) to trust instead of the ones Node.js is configured to trust. This refers to the value of the certificate(s) and not a filename of the certificate(s). This is passed as the ca option for the underlying [tls.createSecureContext()] call (or underlying [crypto.createCredentials()] if using Node.js below 0.12).
  • cert: The client certificate to use in the SSL handshake. This is passed as the cert option for the underlying [tls.createSecureContext()] call (or underlying [crypto.createCredentials()] if using Node.js below 0.12).
  • ciphers: The ciphers to use to use in the SSL handshake instead of the default ones for Node.js. This is passed as the ciphers option for [tls.createSecureContext()] call (or underlying [crypto.createCredentials()] if using Node.js below 0.12).
  • maxVersion: This is passed as the maxVersion option for the underlying [tls.createSecureContext()] call.
  • minVersion: This is passed as the minVersion option for the underlyi

Issues· 176 open

View all issuesOpen on GitHub
  • #2573

    Unable to use the question mark (?) character inside a string.

    Updated Aug 26, 2026
  • #2580

    Docs: mention MariaDB in README (CI already tests MariaDB)

    Updated May 15, 2026
  • #2529

    Problems with transaction

    needs more infoUpdated Apr 18, 2026
  • #2377

    ER_NOT_SUPPORTED_AUTH_MODE with mysql_native_password

    Updated Apr 6, 2026
  • #2576

    Maintainer

    Updated Jan 4, 2026
  • #2571

    Setting incorrect value for `timestamp` causes date to be set as UTC and to return as a string

    Updated Sep 9, 2025
  • #2563

    Updating URL parsing to WHATWG URL

    featureUpdated Aug 14, 2025
  • #2565

    RangeError: The value of "offset" is out of range. It must be >= 0 and <= 5254. Received 5261

    needs investigationUpdated Nov 23, 2023
  • #2561

    the connection string is parsed wrongly

    bugUpdated Nov 20, 2023
  • #731

    Security issue with param escaping?

    securityUpdated Mar 27, 2023

> Tags

JavaScriptjavascriptmysqlnodejs

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库