<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
    // 数据库连接信息
    String url = "jdbc:mysql://localhost:3306/test";
    String user = "SchoolST";
    String password = "123456";

    // 创建表的 SQL 语句
    String createTablesSQL = ""
            + "CREATE TABLE IF NOT EXISTS teachers ("
            + "    teacher_id INT AUTO_INCREMENT PRIMARY KEY, "
            + "    name VARCHAR(255) NOT NULL, "
            + "    college VARCHAR(255) NOT NULL"
            + ");"

            + "CREATE TABLE IF NOT EXISTS courses ("
            + "    course_id INT AUTO_INCREMENT PRIMARY KEY, "
            + "    course_name VARCHAR(255) NOT NULL, "
            + "    teacher_id INT, "
            + "    FOREIGN KEY (teacher_id) REFERENCES teachers(teacher_id)"
            + ");"

            + "CREATE TABLE IF NOT EXISTS dimensions ("
            + "    dimension_id INT AUTO_INCREMENT PRIMARY KEY, "
            + "    name VARCHAR(255) NOT NULL, "
            + "    weight FLOAT NOT NULL"
            + ");"

            + "CREATE TABLE IF NOT EXISTS questions ("
            + "    question_id INT AUTO_INCREMENT PRIMARY KEY, "
            + "    question_text VARCHAR(255) NOT NULL, "
            + "    dimension_id INT, "
            + "    FOREIGN KEY (dimension_id) REFERENCES dimensions(dimension_id)"
            + ");"

            + "CREATE TABLE IF NOT EXISTS evaluations ("
            + "    evaluation_id INT AUTO_INCREMENT PRIMARY KEY, "
            + "    student_id VARCHAR(255) NOT NULL, "
            + "    teacher_id INT, "
            + "    course_id INT, "
            + "    total_score FLOAT, "
            + "    FOREIGN KEY (teacher_id) REFERENCES teachers(teacher_id), "
            + "    FOREIGN KEY (course_id) REFERENCES courses(course_id)"
            + ");"

            + "CREATE TABLE IF NOT EXISTS evaluation_answers ("
            + "    answer_id INT AUTO_INCREMENT PRIMARY KEY, "
            + "    evaluation_id INT, "
            + "    question_id INT, "
            + "    answer VARCHAR(255), "
            + "    FOREIGN KEY (evaluation_id) REFERENCES evaluations(evaluation_id), "
            + "    FOREIGN KEY (question_id) REFERENCES questions(question_id)"
            + ");";

    try {
        // 加载数据库驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        // 建立连接
        Connection conn = DriverManager.getConnection(url, user, password);

        // 执行创建表的 SQL 语句
        Statement stmt = conn.createStatement();
        stmt.execute(createTablesSQL);

        // 输出调试信息
        out.println("数据库表初始化成功！");
    } catch (Exception e) {
        e.printStackTrace();
        out.println("数据库表初始化失败：" + e.getMessage());
    }
%>
