cd my-express-app
npm i mysql -S
// app.js
const express = require('express');
const mysql = require('mysql2');

配置mysql

// dbConfig.js
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: 'your_password',
  database: 'your_database'
};

const pool = mysql.createPool(dbConfig);

在express应用中设置路由,用于处理与MySQL数据库的交互:

 // 查询操作
app.get('/users', (req, res) => {
  const sql = 'SELECT * FROM users';
  pool.query(sql, (error, results) => {
    if (error) throw error;
    res.json(results);
  });
});

// 插入操作
app.post('/users', (req, res) => {
  const user = req.body;
  const sql = 'INSERT INTO users (username, password) VALUES (?, ?)';
  pool.query(sql, [user.username, user.password], (error, results) => {
    if (error) throw error;
    res.json({ message: 'User created successfully', id: results.insertId });
  });
});

// 更新操作
app.put('/users/:id', (req, res) => {
  const id = req.params.id;
  const updates = req.body;
  const sql = 'UPDATE users SET username = ?, password = ? WHERE id = ?';
  pool.query(sql, [updates.username, updates.password, id], (error, results) => {
    if (error) throw error;
    res.json({ message: 'User updated successfully', affectedRows: results.affectedRows });
  });
});

// 删除操作
app.delete('/users/:id', (req, res) => {
  const id = req.params.id;
  const sql = 'DELETE FROM users WHERE id = ?';
  pool.query(sql, [id], (error, results) => {
    if (error) throw error;
    res.json({ message: 'User deleted successfully', affectedRows: results.affectedRows });
  });
});

启动Express应用

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐