from flask import Flask, jsonify, request
import mysql.connector
app = Flask(__name__)
# 连接到MySQL数据库
db_connection = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
cursor = db_connection.cursor()
@app.route('/users', methods=['GET'])
def get_users():
cursor.execute("SELECT * FROM users")
users = cursor.fetchall()
return jsonify([dict(zip(('id', 'name', 'email'), row)) for row in users])
@app.route('/users/<int:id>', methods=['GET'])
def get_user(id):
cursor.execute("SELECT * FROM users WHERE id = %s", (id,))
user = cursor.fetchone()
return jsonify(dict(zip(('id', 'name', 'email'), user)))
@app.route('/users', methods=['POST'])
def add_user():
name = request.json['name']
email = request.json['email']
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", (name, email))
db_connection.commit()
return jsonify({'message': 'User added successfully'}), 201
@app.route('/users/<int:id>', methods=['PUT'])
def update_user(id):
name = request.json['name']
email = request.json['email']
cursor.execute("UPDATE users SET name = %s, email = %s WHERE id = %s", (name, email, id))
db_connection.commit()
return jsonify({'message': 'User updated successfully'}), 200
@app.route('/users/<int:id>', methods=['DELETE'])
def delete_user(id):
cursor.execute("DELETE FROM users WHERE id = %s", (id,))
db_connection.commit()
return jsonify({'message': 'User deleted successfully'}), 200
if __name__ == '__main__':
app.run(debug=True)
这段代码提供了一个简单的用户管理系统的框架,包括了用户的增删改查操作。在实际应用中,你需要根据自己的数据库结构和需求来调整SQL语句。记得替换掉连接数据库的用户名、密码和数据库名称,并确保你的MySQL数据库中有一个名为users
的表,具有id
, name
, email
这些字段。