This topic describes how to use the MySQL driver package for Node.js to connect to an AnalyticDB for MySQL cluster.
Prerequisites
- Node.js is downloaded and installed. For information about where to download Node.js, see Node.js.
- The MySQL driver package for Node.js is installed.
Precautions
- If the host where Node.js is installed, such as an Elastic Compute Service (ECS) instance, belongs to the same virtual private cloud (VPC) as your AnalyticDB for MySQL cluster, use the internal endpoint to connect to the cluster. Otherwise, apply for a public endpoint for the AnalyticDB for MySQL cluster. For more information, see Apply for or release a public endpoint.
- The IP address of the Node.js host is added to a whitelist of the AnalyticDB for MySQL cluster. For more information, see Configure a whitelist.
Connect to an AnalyticDB for MySQL cluster
var mysql = require('mysql');
var connection = mysql.createConnection({
// The endpoint that is used to connect to the AnalyticDB for MySQL cluster. You can obtain the endpoint from the Cluster Information page of the AnalyticDB for MySQL console.
host: 'am-bp***.ads.aliyuncs.com',
// The port number that is used to connect to the AnalyticDB for MySQL cluster.
port: 3306,
// The name of the account that is used to connect to the AnalyticDB for MySQL cluster. The account can be a privileged account or a standard account.
user: 'account_name',
// The password of the account that is used to connect to the AnalyticDB for MySQL cluster.
password: 'account_password',
// The name of the database in the AnalyticDB for MySQL cluster.
database: 'db_name',
// The timeout period for establishing a connection. Default value: 10000. Unit: milliseconds.
connectTimeout: 10000
});
connection.connect(function(err) {
if (err) {
throw err;
}
console.log("Connection established.");
connection.query('SELECT count(*) AS count FROM information_schema.tables', function(err1, results, fields) {
if (err1) {
throw err1;
}
console.log('Count: ' + results[0].count);
});
connection.end(function(err2) {
if (err2) {
throw err2;
}
console.log("Connection closed.");
});
});