Home > Web Front-end > Front-end Q&A > How to connect nodejs to mysql

How to connect nodejs to mysql

下次还敢
Release: 2024-04-21 05:06:55
Original
557 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

<code class="shell">npm install mysql</code>
Copy after login

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

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

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

5. Close the connection

<code class="javascript">connection.end((err) => {
  // ...
});</code>
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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template