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

What is the method to convert nodejs mysql to json

WBOY
Release: 2023-06-04 12:13:08
forward
1685 people have browsed it

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

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!

Related labels:
source:yisu.com
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