Connect to an AnalyticDB for MySQL cluster using the mysql driver package for Node.js.
Prerequisites
Before you begin, ensure that you have:
Node.js installed. Download it from nodejs.org
The
mysqldriver package installed. Run the following command to install it:npm install mysql --saveThe IP address of your Node.js host added to a whitelist of your cluster. See Configure a whitelist
A cluster endpoint. Retrieve it from the Cluster Information page of the AnalyticDB for MySQL console:
If your Node.js host (for example, an Elastic Compute Service (ECS) instance) is in the same virtual private cloud (VPC) as your cluster, use the internal endpoint
Otherwise, apply for a public endpoint. See Apply for or release a public endpoint
Connect to an AnalyticDB for MySQL cluster
Store your credentials as environment variables rather than hardcoding them in your source code.
Set the following environment variables before running the sample:
| Variable | Description | Example |
|---|---|---|
ADB_HOST | Cluster endpoint | am-bp***.ads.aliyuncs.com |
ADB_PORT | Port number | 3306 |
ADB_USER | Account name (privileged or standard) | account_name |
ADB_PASSWORD | Account password | account_password |
ADB_DATABASE | Database name | db_name |
The following sample connects to the cluster, runs a query, and closes the connection:
// Step 1: Import the mysql driver.
const mysql = require('mysql');
// Step 2: Create a connection using credentials from environment variables.
const connection = mysql.createConnection({
host: process.env.ADB_HOST,
port: parseInt(process.env.ADB_PORT, 10) || 3306,
user: process.env.ADB_USER,
password: process.env.ADB_PASSWORD,
database: process.env.ADB_DATABASE,
// Timeout for establishing the connection. Default: 10000 ms.
connectTimeout: 10000,
});
// Step 3: Open the connection.
connection.connect((err) => {
if (err) throw err;
console.log('Connection established.');
// Step 4: Run a query.
connection.query(
'SELECT count(*) AS count FROM information_schema.tables',
(err, results) => {
if (err) throw err;
console.log('Count:', results[0].count);
// Step 5: Close the connection.
connection.end((err) => {
if (err) throw err;
console.log('Connection closed.');
});
}
);
});When the code runs successfully, the output is similar to:
Connection established.
Count: 42
Connection closed.Usage notes
Use a connection pool in production. Creating a new connection for each request adds latency. Use
mysql.createPool()to manage a pool of reusable connections. See the mysql documentation for details.Use parameterized queries to prevent SQL injection. The
mysqlpackage escapes query values on the client side. Pass user-supplied values as parameters rather than interpolating them into SQL strings. See Escaping query values for examples.