Home  >  Article  >  Web Front-end  >  nodejs query database return

nodejs query database return

王林
王林Original
2023-05-25 09:40:08724browse

Node.js is a lightweight JavaScript runtime environment that can use JavaScript to write server-side code, supports asynchronous I/O and event-driven models, and is very suitable for building highly scalable network applications. When developing web applications, it is often necessary to interact with the database, such as querying user information, retrieving order history, etc. This article will introduce how to query the database and return data in Node.js.

Select database

Before we start querying the database, we need to select the database we want to use. Node.js supports many popular databases such as MongoDB, MySQL, and PostgreSQL. Each database has its advantages and disadvantages, and the appropriate database should be selected based on project needs. In this article, we will use the MySQL database.

Install MySQL

Before using the MySQL database, we need to install MySQL first. On Ubuntu, you can use the following command:

sudo apt-get update
sudo apt-get install mysql-server

On Windows, you can download the installer from the MySQL official website and follow the prompts to install it.

Connect to MySQL database

In Node.js, we can use the npm package mysql to interact with the MySQL database. To use this library, we need to install it first. You can use the following command:

npm install mysql

Connecting to a MySQL database requires creating a connection pool, which will be responsible for managing all connections to the database. The following is a sample code to connect to a MySQL database:

const mysql = require('mysql');

const pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

pool.getConnection((err, connection) => {
  if (err) throw err;
  console.log('Connected to MySQL');
})

In the example, we create a connection pool using the mysql.createPool method and pass some options such as maximum number of connections, hostname, user name, password and database name to connect to. Then, we use the pool.getConnection method to get a connection from the connection pool. If successful, a "Connected to MySQL" message will be printed.

Query database

After connecting to the MySQL database, we can use the connection object to query the database. The following is a sample code to query all users in the MySQL database:

const mysql = require('mysql');

const pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'database_name'
});

pool.getConnection((err, connection) => {
  if (err) throw err;

  connection.query('SELECT * FROM users', (err, rows) => {
    if (err) throw err;

    console.log(rows);
    connection.release();
  });
});

In this example, we use the connection.query method to query all users in the MySQL database. This method accepts two parameters: a string containing the SQL query and a callback function. If the query is successful, the second parameter of the callback function will be an array containing all query results. In this example, we print the results to the console and release the database connection using the connection.release method.

The query results can be further processed. For example, we can use the Array.map method to convert the result into an array of objects:

rows = rows.map(row => {
  return {
    id: row.id,
    name: row.name,
    email: row.email
  };
});

In the example, we use the Array.map method to convert each row object in the result into an object with ID, name and electron An object of mail properties.

Limit the results

In some cases, you may need to limit the query results, such as only returning the top ten results. In MySQL, you can use the LIMIT clause to limit results. Here is a sample code that shows how to limit the results:

connection.query('SELECT * FROM users LIMIT 10', (err, rows) => {
  if (err) throw err;

  console.log(rows);
  connection.release();
});

In this example, we use the LIMIT clause to limit the results to only the first ten rows.

Filter results

In some cases, it may be necessary to filter query results based on specific conditions. In MySQL, you can use the WHERE clause to filter results. Here is a sample code that shows how to use the WHERE clause to filter the results:

connection.query('SELECT * FROM users WHERE age > 18', (err, rows) => {
  if (err) throw err;

  console.log(rows);
  connection.release();
});

In this example, we use the WHERE clause to filter the results to only include users who are older than 18 years old.

Summary

In this article, we introduced how to query a MySQL database and return results in Node.js. First, we connect to the MySQL database, then execute the query and process the results using a callback function. We also discussed how to limit and filter the results and further process the results. Hope this article can help you query the database in Node.js.

The above is the detailed content of nodejs query database return. 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