nodejs mysql to json

WBOY
Release: 2023-05-08 18:45:08
Original
639 people have browsed it

In actual development, it is often necessary to convert the data queried in MySQL into JSON format for subsequent data processing and transmission. In Node.js, there are some methods to convert data in the MySQL database into JSON format.

1. Install the MySQL module

To connect to MySQL in Node.js, you need to install the MySQL module first. You can install it through the following command:

npm install mysql
Copy after login

2. Connect to the MySQL database

After installing the MySQL module, you need to connect to the MySQL database. You can create a database connection through the following code:

const mysql = require('mysql');

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

connection.connect();
Copy after login

Here, you need to make corresponding modifications according to the database you are connected to, such as database address, user name, password, etc.

3. Query data

After connecting to the MySQL database, you can use the connection.query() method to query the data. This method requires passing in a SQL query statement and a callback function. The first parameter of the callback function is the queried data. For example:

connection.query('SELECT * FROM users', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results);
});
Copy after login

Here we query the users table in the database and print out the queried data.

4. Convert data to JSON

After getting the queried data, you need to convert it to JSON format. This can be achieved through the following methods:

connection.query('SELECT * FROM users', function (error, results) {
  if (error) throw error;
  const json = JSON.stringify(results);
  console.log(json);
});
Copy after login

The JSON.stringify() method is used here to convert the queried data into a JSON format string to facilitate subsequent data processing and transmission.

Summary

In Node.js, the process of converting data in the MySQL database to JSON format is very simple. You only need to connect to the database, query the data and convert the data. The code provided above is for reference only and can be modified and optimized according to your actual needs.

The above is the detailed content of nodejs mysql to json. For more information, please follow other related articles on the PHP Chinese website!

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