How to connect nodejs to mysql database

下次还敢
Release: 2024-04-21 06:13:01
Original
938 people have browsed it

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

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 install mysql2 Driver:

<code class="Bash">npm install mysql2</code>
Copy after login

2 . Create a MySQL connection

Use the mysql2.createConnection() function to create a connection object:

<code class="JavaScript">const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: 'password',
  database: 'database_name'
});</code>
Copy after login

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 the connection.query() method to execute the query:

<code class="JavaScript">connection.query('SELECT * FROM table_name', (err, results) => {
  if (err) throw err;

  console.log(results);
});</code>
Copy after login

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 is null.
  • results: Array containing query results.

4. End the connection

After using the connection object, remember to use the connection.end() method to end the connection:

<code class="JavaScript">connection.end();</code>
Copy after login

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!

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
Popular Tutorials
More>
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!