
Node.js- Express框架连接 MySQL 数据库
在 Express.js 中连接 MySQL 数据库通常需要使用一个 MySQL 驱动程序。其中,mysql2是一个流行的 Node.js MySQL 驱动程序,提供了更好的性能和一些新特性。以下是连接 MySQL 数据库并在 Express.js 中使用mysql2。
·
在 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 官方文档。
更多推荐
所有评论(0)