给我一个利用pythonflask框架操作mysql数据库的代码
时间: 2023-12-02 14:58:33 浏览: 101
在Python的Flask框架下使用sqlalchemy库的简单教程
好的,以下是一个利用Python Flask框架操作MySQL数据库的代码示例:
```python
from flask import Flask, jsonify, request
import pymysql
app = Flask(__name__)
db = pymysql.connect(host='localhost', user='root', password='password', db='example_db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
@app.route('/users', methods=['GET'])
def get_all_users():
try:
cursor = db.cursor()
cursor.execute("SELECT * FROM users")
result = cursor.fetchall()
return jsonify(result), 200
except:
return jsonify({'error': 'Something went wrong'}), 500
finally:
cursor.close()
@app.route('/users', methods=['POST'])
def add_user():
try:
data = request.json
name = data.get('name')
email = data.get('email')
cursor = db.cursor()
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", (name, email))
db.commit()
return jsonify({'success': 'User added successfully'}), 201
except:
db.rollback()
return jsonify({'error': 'Something went wrong'}), 500
finally:
cursor.close()
if __name__ == '__main__':
app.run(debug=True)
```
注意,为了新建用户,你需要在MySQL的数据库中创建一个 `users` 表,字段为 `name` 和 `email`。
阅读全文