如何利用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
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()
<!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 survey_app.py
以上是如何利用MySQL和Python開發一個簡單的線上問卷的詳細內容。更多資訊請關注PHP中文網其他相關文章!