Node.js- Express框架连接 MySQL 数据库

在 Express.js 中连接 MySQL 数据库通常需要使用一个 MySQL 驱动程序。其中,mysql2 是一个流行的 Node.js MySQL 驱动程序,提供了更好的性能和一些新特性。以下是连接 MySQL 数据库并在 Express.js 中使用 mysql2 的详细讲解:

1. 安装 mysql2

首先,你需要通过 npm 安装 mysql2

npm install mysql2

2. 连接 MySQL 数据库:

在 Express.js 应用中,你可以使用 mysql2 来连接到 MySQL 数据库。在你的 Express 应用中,你可以创建一个单独的模块来处理数据库连接。以下是一个例子:

// db.js

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'your-username',
  password: 'your-password',
  database: 'your-database-name',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

const connectDB = async () => {
  try {
    const connection = await pool.getConnection();
    console.log('MySQL Connected');
    connection.release();
  } catch (error) {
    console.error('Error connecting to MySQL:', error);
  }
};

module.exports = connectDB;

然后在你的 Express 应用中引入并调用 connectDB 函数:

// app.js

const express = require('express');
const connectDB = require('./db');

const app = express();
const port = 3000;

// 连接到 MySQL 数据库
connectDB();

app.get('/', (req, res) => {
  res.send('Hello, Express with MySQL!');
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

3. 执行 SQL 查询:

使用 mysql2 执行 SQL 查询非常简单。以下是一个例子,展示了如何在 Express.js 中执行 SQL 查询:

// app.js

const express = require('express');
const connectDB = require('./db');

const app = express();
const port = 3000;

// 连接到 MySQL 数据库
connectDB();

app.get('/get-users', async (req, res) => {
  try {
    // 执行 SQL 查询
    const [rows, fields] = await pool.execute('SELECT * FROM users');
    res.json(rows);
  } catch (error) {
    res.status(500).json({ error: 'Error fetching users' });
  }
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

4. 使用参数化查询:

为了防止 SQL 注入攻击,最好使用参数化查询。以下是一个例子:

// app.js

const express = require('express');
const connectDB = require('./db');

const app = express();
const port = 3000;

// 连接到 MySQL 数据库
connectDB();

app.get('/get-user/:id', async (req, res) => {
  const userId = req.params.id;

  try {
    // 使用参数化查询
    const [rows, fields] = await pool.execute('SELECT * FROM users WHERE id = ?', [userId]);
    res.json(rows);
  } catch (error) {
    res.status(500).json({ error: 'Error fetching user' });
  }
});

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

以上是使用 mysql2 连接 MySQL 数据库并在 Express.js 中执行查询的基本方法。mysql2 的官方文档是学习更多内容的好资源:mysql2 官方文档

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[猫玖]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值