Home  >  Article  >  Web Front-end  >  How to connect nodejs to mysql

How to connect nodejs to mysql

下次还敢
下次还敢Original
2024-04-21 05:06:55533browse

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>

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

Statement:
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