Express MySQL Integration Guide

In Express, you can utilize the MySQL module to connect with and manipulate MySQL databases. Here’s a simple example demonstrating how to use MySQL in Express:

  1. Firstly, the MySQL module needs to be installed.
npm install mysql
  1. Introducing the mysql module in an Express application and establishing a database connection.
const mysql = require('mysql');

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

connection.connect((err) => {
  if (err) {
    console.error('Error connecting to MySQL: ' + err.stack);
    return;
  }
  console.log('Connected to MySQL as id ' + connection.threadId);
});
  1. You can execute SQL queries to operate on databases.
app.get('/users', (req, res) => {
  connection.query('SELECT * FROM users', (err, results) => {
    if (err) {
      console.error('Error querying MySQL: ' + err.stack);
      return;
    }
    res.json(results);
  });
});

app.post('/users', (req, res) => {
  const { username, email } = req.body;
  connection.query('INSERT INTO users (username, email) VALUES (?, ?)', [username, email], (err, result) => {
    if (err) {
      console.error('Error inserting into MySQL: ' + err.stack);
      return;
    }
    res.send('User added successfully');
  });
});

In the code example above, we establish a database connection and perform queries and inserts using the connection.query method. In actual applications, various types of SQL operations can be executed as needed to interact with the MySQL database.

bannerAds