How to connect nodejs to mysql

下次还敢
Release: 2024-04-21 05:06:55
Original
442 people have browsed it

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 connect nodejs to mysql

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
Copy after login

2. Create a MySQL connection

const mysql = require('mysql'); const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'my_password', database: 'my_database' });
Copy after login

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); });
Copy after login

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); });
Copy after login

5. Close the connection

connection.end((err) => { // ... });
Copy after login

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 database

The 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!