node连接mysql
准备工作
1、创建一个新的文件夹demo来存放你的项目
2、在demo目录下npm init -y初始化项目
3、安装Express,使用Express框架来简化HTTP服务器的创建和管理。npm install express
4、创建基本的HTTP服务
// index.js const express = require('express'); const app = express(); const port = 3000; // 中间件,用于解析JSON请求体 app.use(express.json()); // 定义一个简单的路由 app.get('/', (req, res) => { res.send('Hello World!'); }); // 启动服务器 app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
5、运行服务器
node index.js
6、安装mysql2包
npm install mysql2
7. 配置数据库连接
在你的index.js文件中配置MySQL数据库连接。你需要提供数据库的主机名、用户名、密码和数据库名称。
8. 使用连接池
为了提高性能和资源利用率,建议使用连接池来管理数据库连接。
const express = require('express');
const mysql = require('mysql2/promise'); // 使用mysql2/promise以支持Promise
const app = express();
const port = 3000;
// 中间件,用于解析json请求体
app.use(express.json());
// 创建MySQL连接池
const pool = mysql.createPool({
host: 'localhost', // 数据库主机名
user: 'your_username', // 数据库用户名
password: 'your_password', // 数据库密码
database: 'your_database', // 数据库名称
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// 定义一个简单路由
app.get('/', (req, res) => {
res.send('Hello World!');
});
// 示例路由,查询数据库
app.get('/users', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM users');
res.json(rows);
} catch (error) {
console.error('Error querying database:', error);
res.status(500).send('Internal Server Error');
}
});
// 启动服务器
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
浙公网安备 33010602011771号