Home  >  Article  >  Database  >  What is the method to convert nodejs mysql to json

What is the method to convert nodejs mysql to json

WBOY
WBOYforward
2023-06-04 12:13:081641browse

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

2. Connect to 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();

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);
});

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);
});

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

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

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete