数据库未从Ajax POST更新通常指的是在前端通过Ajax发送POST请求到服务器,期望能够更新数据库中的数据,但实际数据库并未发生改变。这种情况可能由多种原因导致,包括但不限于:
from flask import Flask, request, jsonify
import mysql.connector
app = Flask(__name__)
@app.route('/update_data', methods=['POST'])
def update_data():
data = request.get_json()
# 数据验证
if not data or 'id' not in data or 'value' not in data:
return jsonify({'error': 'Invalid data'}), 400
try:
# 连接数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = db.cursor()
# 更新数据库
sql = "UPDATE yourtable SET value = %s WHERE id = %s"
val = (data['value'], data['id'])
cursor.execute(sql, val)
db.commit()
return jsonify({'success': True}), 200
except mysql.connector.Error as err:
return jsonify({'error': str(err)}), 500
finally:
if db.is_connected():
cursor.close()
db.close()
if __name__ == '__main__':
app.run(debug=True)
领取专属 10元无门槛券
手把手带您无忧上云