
如何利用MySQL和Python开发一个简单的在线调查问卷
简介
在线调查问卷在现代社会中被广泛使用,用于收集用户的观点、反馈和意见。本文将介绍如何使用MySQL和Python开发一个简单的在线调查问卷系统,并提供相关的代码示例。
一、数据库设计
创建一个名为survey的数据库:
立即学习“Python免费学习笔记(深入)”;
CREATE DATABASE survey;
创建名为questions和responses的表:
创建questions表,用于存储调查问卷的问题:
CREATE TABLE questions ( id INT PRIMARY KEY AUTO_INCREMENT, question_text VARCHAR(255) NOT NULL );
创建responses表,用于存储用户的答案:
CREATE TABLE responses ( id INT PRIMARY KEY AUTO_INCREMENT, question_id INT, response_text VARCHAR(255) NOT NULL, FOREIGN KEY (question_id) REFERENCES questions(id) );
二、Python代码实现
导入必要的库:
import mysql.connector from mysql.connector import Error from flask import Flask, request, render_template
连接到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.commit()
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>三、运行和测试
在终端中运行Python代码:
python survey_app.py
结论
本文介绍了如何使用MySQL和Python开发一个简单的在线调查问卷系统。通过数据库设计和相关的代码实现,可以方便地收集用户的观点、反馈和意见。通过丰富前端页面的设计和功能,可以进一步提升问卷的用户体验。希望本文能对读者有所帮助,以及启发更多创新的思路。
以上就是如何利用MySQL和Python开发一个简单的在线调查问卷的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号