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

How to connect nodejs to mysql

PHPz
PHPzOriginal
2023-05-11 19:35:061170browse

Node.js is a JavaScript runtime environment that can run JavaScript code on the server side and client side. Node.js provides powerful tools and modules that allow developers to easily interact with various databases. MySQL is a popular relational database widely used in web development. In this article, we will learn how to connect to a MySQL database using Node.js.

  1. Installing MySQL

Before you start connecting to MySQL, you need to install the MySQL server on your local system and start it. You can download and install MySQL Community Server from the official website (https://dev.mysql.com/downloads/mysql/). After the installation is complete, start the MySQL server.

  1. Install the MySQL module

Connecting Node.js to MySQL requires a module called "mysql". You can install it using npm, Node.js’s package manager. Open the command line tool and run the following command:

npm install mysql
  1. Connect to MySQL

After installing the "mysql" module, we need to introduce it in the Node.js application , and use it to connect to the MySQL database. The following is a sample code that connects to MySQL and queries all records of the "users" table:

const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mydatabase'
});

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected!');
  connection.query('SELECT * FROM users', (err, rows) => {
    if (err) throw err;

    console.log('Data received from MySQL:
');
    console.log(rows);
  });
});

In this example, we create a MySQL connection object using the "mysql" module. We specified the MySQL server's hostname "localhost", username "root", password "password" and database name "mydatabase".

After calling the "connect" method on the connection object, we use the "query" method to execute the SQL query. After the query is successful, we will print the query results to the console.

  1. Querying and updating data

Querying and updating data in a MySQL database is a common task. The following is the code for some sample query and update operations:

Query data:

// 查询users表的所有记录
connection.query('SELECT * FROM users', (err, rows) => {
  if (err) throw err;

  console.log('Data received from MySQL:
');
  console.log(rows);
});

// 查询ID为1的用户
connection.query('SELECT * FROM users WHERE id = ?', [1], (err, rows) => {
  if (err) throw err;

  console.log('Data received from MySQL:
');
  console.log(rows);
});

Update data:

// 将ID为1的用户的名字改为John
connection.query('UPDATE users SET name = ? WHERE id = ?', ['John', 1], (err, result) => {
  if (err) throw err;

  console.log(`Changed ${result.changedRows} rows`);
});
  1. Error handling

Errors may occur when connecting and querying the MySQL database. To ensure the stability of the code, we need to include appropriate error handling code in the code. Here is a sample error handling code:

connection.connect((err) => {
  if (err) throw err;
  console.log('Connected!');

  connection.query('SELECT * FROM non_existing_table', (err, rows) => {
    if (err) {
      console.log('Error executing query:', err);
    } else {
      console.log('Data received from MySQL:
');
      console.log(rows);
    }
  });
});

In this example, we are deliberately trying to query a table that does not exist. If the query fails, we will catch the error and print the error message.

Conclusion

This is a simple guide on how to connect and operate a MySQL database in Node.js. MySQL programming with Node.js can be more efficient, but you still need to handle errors and exceptions appropriately. I hope this article can make you happily use Node.js to connect to MySQL 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