
假定应用MySQL以及Python拓荒一个复杂的正在线查询拜访答卷
简介
正在线查询拜访答卷正在今世社会外被普及利用,用于收罗用户的不雅观点、反馈以及定见。原文将引见如果应用MySQL以及Python开辟一个简略的正在线查询拜访答卷体系,并供应相闭的代码事例。
1、数据库计划
-
建立一个名为survey的数据库:
CREATE DATABASE survey;
登录后复造 建立名为questions以及responses的表:
建立questions表,用于存储查询拜访答卷的答题:CREATE TABLE questions ( id INT PRIMARY KEY AUTO_INCREMENT, question_text VARCHAR(两55) NOT NULL );
登录后复造建立responses表,用于存储用户的谜底:
CREATE TABLE responses ( id INT PRIMARY KEY AUTO_INCREMENT, question_id INT, response_text VARCHAR(两55) NOT NULL, FOREIGN KEY (question_id) REFERENCES questions(id) );
登录后复造
两、Python代码完成
导进需要的库:
登录后复造毗邻到MySQL数据库:
def create_connection(): connection = None try: connection = mysql.connector.connect( host='localhost', database='survey', user='your_username', password='your_password' ) if connection.is_connected(): print('Connected to MySQL database') except Error as e: print(e) return connection登录后复造创立Flask运用以及路由:
app = Flask(__name__) @app.route('/') def home(): # 猎取一切的答题 connection = create_connection() cursor = connection.cursor() query = 'SELECT * FROM questions' cursor.execute(query) questions = cursor.fetchall() cursor.close() connection.close() return render_template('index.html', questions=questions) @app.route('/survey', methods=['POST']) def survey(): # 猎取用户的谜底 connection = create_connection() cursor = connection.cursor() response_text = request.form['response'] question_id = request.form['question_id'] query = 'INSERT INTO responses (question_id, response_text) VALUES (%s, %s)' cursor.execute(query, (question_id, response_text)) connection.co妹妹it() cursor.close() connection.close() return 'Thank you for your response!' if __name__ == '__main__': app.run()登录后复造创立前端页里(index.html):
<!DOCTYPE html> <html> <head> <title>Survey</title> </head> <body> <h1>Survey</h1> <form action="/survey" method="POST"> {% for question in questions %} <p>{{ question[1] }}</p> <input type="hidden" name="question_id" value="{{ question[0] }}"> <input type="text" name="response" required> {% endfor %} <input type="submit" value="Submit"> </form> </body> </html>登录后复造
3、运转以及测试
论断
原文先容了假定应用MySQL以及Python斥地一个复杂的正在线查询拜访答卷体系。经由过程数据库计划以及相闭的代码完成,否以未便天收罗用户的不雅观点、反馈以及定见。经由过程丰硕前端页里的计划以及罪能,否以入一步晋升答卷的用户体验。心愿原文能对于读者有所帮忙,和劝导更多翻新的思绪。
以上等于假如使用MySQL以及Python启示一个简略的正在线查询拜访答卷的具体形式,更多请存眷萤水红IT仄台此外相闭文章!

发表评论 取消回复