To connect to a MySQL database, you need to follow the following steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.
How to use Node.js to connect to MySQL database
In order to use Node.js to connect to MySQL database, you need to follow the following Steps:
1. Install the MySQL driver
Use npm to installmysql2
Driver:
npm install mysql2
2 . Create a MySQL connection
Use themysql2.createConnection()
function to create a connection object:
const mysql = require('mysql2'); const connection = mysql.createConnection({ host: 'localhost', port: 3306, user: 'root', password: 'password', database: 'database_name' });
Among them:
host
: The host address or IP address of the database.port
: The port number of the database.user
: Username to connect to the database.password
: Password for connecting to the database.database
: The name of the database to be connected.3. Execute the query
Use theconnection.query()
method to execute the query:
connection.query('SELECT * FROM table_name', (err, results) => { if (err) throw err; console.log(results); });
where:
'SELECT * FROM table_name'
: SQL query to be executed.(err, results)
: Callback function, executed when the query is completed.err
: If an error occurs in the query, error information is included; otherwise, it isnull
.results
: Array containing query results.4. End the connection
After using the connection object, remember to use theconnection.end()
method to end the connection:
connection.end();
The above is the detailed content of How to connect nodejs to mysql database. For more information, please follow other related articles on the PHP Chinese website!