Node.js-使用express对mysql数据库进行增删改查的demo
在本文中,我们将深入探讨如何使用Node.js的Express框架与MySQL数据库进行交互,实现数据的增删改查操作。Express是Node.js中最流行的Web应用程序框架,它简化了服务器端编程,使得开发人员能够快速构建高效、可扩展的网络应用。确保已安装Node.js环境。接下来,我们需要安装以下npm(Node包管理器)包: 1. express:用于构建Web应用。 2. express-session:用于处理用户会话。 3. body-parser:解析HTTP请求体。 4. mysql2:提供与MySQL数据库的连接。通过命令行运行以下命令来安装这些依赖包: ```bash npm install express-session body-parser mysql2 ```创建一个名为`app.js`的文件,初始化Express应用。首先引入所需模块,然后设置路由和中间件: ```javascript const express = require('express'); const session = require('express-session'); const bodyParser = require('body-parser'); const mysql = require('mysql2'); const app = express(); //使用session中间件app.use(session({ secret: 'your_secret_key', resave: false, saveUninitialized: true, })); //解析请求体app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); //创建MySQL连接const connection = mysql.createConnection({ host: 'localhost', user: 'your_user', password: 'your_password', database: 'your_database' }); connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL database!'); }); ```现在,让我们创建一个简单的CRUD(Create, Read, Update, Delete)接口。假设我们有一个名为`users`的表,包含`id`, `username`和`email`字段。 1. **创建(Create)**:创建一个新的用户记录。 ```javascript app.post('/api/users', (req, res) => { const { username, email } = req.body; const sql = 'INSERT INTO users SET ?'; const user = { username, email }; connection.query(sql, user, (err, result) => { if (err) throw err; res.json({ status: 'User created successfully', id: result.insertId }); ``` 2. **读取(Read)**:获取所有用户或单个用户记录。 ```javascript app.get('/api/users', (req, res) => { const sql = 'SELECT * FROM users'; connection.query(sql, (err, results) => { if (err) throw err; res.json(results); }); app.get('/api/users/:id', (req, res) => { const userId = req.params.id; const sql = `SELECT * FROM users WHERE id = ${userId}`; connection.query(sql, (err, result) => { if (err) throw err; res.json(result[0]); }); ``` 3. **更新(Update)**:更新用户信息。 ```javascript app.put('/api/users/:id', (req, res) => { const userId = req.params.id; const { username, email } = req.body; const sql = `UPDATE users SET username = ?, email = ? WHERE id = ${userId}`; connection.query(sql, [username, email], (err, result) => { if (err) throw err; if (result.changedRows === 0) { res.status(404).json({ message: 'User not found' }); } else { res.json({ message: 'User updated successfully' }); }); ``` 4. **删除(Delete)**:删除用户记录。 ```javascript app.delete('/api/users/:id', (req, res) => { const userId = req.params.id; const sql = `DELETE FROM users WHERE id = ${userId}`; connection.query(sql, (err, result) => { if (err) throw err; if (result.affectedRows === 0) { res.status(404).json({ message: 'User not found' }); } else { res.json({ message: 'User deleted successfully' }); }); ```启动Express服务器: ```javascript const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); ```这个示例展示了如何使用Express和MySQL在Node.js环境中执行基本的数据库操作。在实际项目中,你可能还需要处理错误、验证输入、使用ORM(对象关系映射)库如Sequelize或TypeORM,以及实现更复杂的业务逻辑。此外,为了生产环境的安全性,应该使用连接池代替直接连接,并且不要在代码中硬编码数据库凭证。
Node.js-使用express对mysql数据库进行增删改查的demo.zip
预估大小:16个文件
nodejs-express-ejs-mysql-master
文件夹
public
文件夹
stylesheets
文件夹
style.css
1KB
readmeImages
文件夹
expMethod.png
11KB
apprender.png
5KB
views
文件夹
index.ejs
2KB
error.ejs
83B
28.87KB
文件大小:
评论区