To read data from a MySQL database in Node.js, you can use the popular mysql2
or mysql
package. Here’s a basic guide using mysql2
:
Step-by-Step Process:
- Install MySQL package: First, you need to install the
mysql2
package using npm.npm install mysql2
- Create a MySQL connection: Set up the MySQL connection to your database.
- Execute a query to read data: Use the
query()
method to fetch data from a specific table.
Example Code:
// Step 1: Import the mysql2 package
const mysql = require('mysql2');
// Step 2: Create a connection to the MySQL database
const connection = mysql.createConnection({
host: 'localhost', // MySQL host
user: 'root', // MySQL user
password: 'password', // MySQL password
database: 'your_database_name' // Your database name
});
// Step 3: Connect to the database
connection.connect((err) => {
if (err) {
console.error('Error connecting: ' + err.stack);
return;
}
console.log('Connected to the database');
});
// Step 4: Query the database to read data
connection.query('SELECT * FROM your_table_name', (err, results) => {
if (err) {
console.error('Error in query: ' + err.stack);
return;
}
console.log('Data from the table:', results);
});
// Step 5: Close the connection
connection.end();
Explanation:
- mysql.createConnection(): Establishes a connection to the MySQL database by specifying connection parameters like
host
,user
,password
, anddatabase
. - connection.query(): Executes a SQL query. In this case,
SELECT * FROM your_table_name
fetches all rows from the specified table. - results: The results of the query are returned as an array of objects, where each object represents a row of data from the table.
- connection.end(): Closes the connection to the database once the operation is complete.
Notes:
- Replace
'your_database_name'
and'your_table_name'
with your actual database and table names. - You can modify the query to fetch specific columns or add conditions (e.g.,
SELECT id, name FROM users WHERE age > 30
).