如何利用MySQL和Python開發一個簡單的在線調查問卷
簡介
在線調查問卷在現代社會中被廣泛使用,用于收集用戶的觀點、反饋和意見。本文將介紹如何使用MySQL和Python開發一個簡單的在線調查問卷系統,并提供相關的代碼示例。
一、數據庫設計
創建一個名為survey的數據庫:
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
登錄后復制在瀏覽器中訪問http://localhost:5000,即可看到調查問卷頁面。
結論
本文介紹了如何使用MySQL和Python開發一個簡單的在線調查問卷系統。通過數據庫設計和相關的代碼實現,可以方便地收集用戶的觀點、反饋和意見。通過豐富前端頁面的設計和功能,可以進一步提升問卷的用戶體驗。希望本文能對讀者有所幫助,以及啟發更多創新的思路。
以上就是如何利用MySQL和Python開發一個簡單的在線調查問卷的詳細內容,更多請關注www.92cms.cn其它相關文章!






