The steps to use Node.js to connect to the MySQL database are as follows: Install the MySQL client library Create a MySQL connection Connect to the MySQL database Query the database Close the connection
How to use Node.js to connect to MySQL
To use Node.js to connect to the MySQL database, you need to follow the following steps:
1. Install the MySQL client library
npm install mysql
2. Create a MySQL connection
const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'my_password', database: 'my_database' });
3. Connect to the MySQL database
connection.connect((err) => { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); });
4. Query the database
connection.query('SELECT * FROM my_table', (err, rows) => { if (err) { console.error('error querying: ' + err.stack); return; } console.log('rows: ', rows); });
5. Close the connection
connection.end((err) => { // ... });
Other connection options
MySQL client library Additional connection options are also provided, including:
host
: Specifies the hostname or IP address of the database server (default is 'localhost')user
: Specify the username used to connect to the databasepassword
: Specify the password used to connect to the databasedatabase
: Specify the database name to connectport
: Specify the port of the database server (default is 3306)ssl
: Specify whether to use SSL connection To databaseThe above is the detailed content of How to connect nodejs to mysql. For more information, please follow other related articles on the PHP Chinese website!