Home > Article > Web Front-end > How to connect nodejs to mysql
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
<code class="shell">npm install mysql</code>
2. Create a MySQL connection
<code class="javascript">const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'my_password', database: 'my_database' });</code>
3. Connect to the MySQL database
<code class="javascript">connection.connect((err) => { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); });</code>
4. Query the database
<code class="javascript">connection.query('SELECT * FROM my_table', (err, rows) => { if (err) { console.error('error querying: ' + err.stack); return; } console.log('rows: ', rows); });</code>
5. Close the connection
<code class="javascript">connection.end((err) => { // ... });</code>
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 database password
: Specify the password used to connect to the database database
: Specify the database name to connect port
: 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!