学生开始考试页面 public static void studentStartExam 从数据库读取题目并逐题显示给学生答题 学生答题完成后计算得分并保存到数据库 连接数据库做完一题可以选择下一题或则完成将代码给出
import java.sql.*;
public class StudentExamPage { private static final String DB_URL = "jdbc:mysql://localhost/exam"; private static final String DB_USER = "root"; private static final String DB_PASSWORD = "123456";
public static void studentStartExam() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
stmt = conn.createStatement();
// 从数据库读取题目
String sql = "SELECT * FROM questions";
rs = stmt.executeQuery(sql);
// 逐题显示给学生答题
while (rs.next()) {
int questionId = rs.getInt("id");
String questionContent = rs.getString("content");
String optionA = rs.getString("option_a");
String optionB = rs.getString("option_b");
String optionC = rs.getString("option_c");
String optionD = rs.getString("option_d");
System.out.println("Question " + questionId + ": " + questionContent);
System.out.println("A. " + optionA);
System.out.println("B. " + optionB);
System.out.println("C. " + optionC);
System.out.println("D. " + optionD);
// 学生答题
System.out.print("Your answer: ");
String studentAnswer = System.console().readLine();
// 保存学生答案到数据库
sql = "INSERT INTO student_answers (question_id, student_answer) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, questionId);
pstmt.setString(2, studentAnswer);
pstmt.executeUpdate();
}
// 计算得分
sql = "SELECT COUNT(*) AS correct_count FROM questions q JOIN student_answers a ON q.id = a.question_id WHERE q.answer = a.student_answer";
rs = stmt.executeQuery(sql);
rs.next();
int correctCount = rs.getInt("correct_count");
int totalScore = correctCount * 10;
// 保存得分到数据库
sql = "INSERT INTO student_scores (score) VALUES (?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, totalScore);
pstmt.executeUpdate();
System.out.println("Your score is " + totalScore);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
原文地址: http://www.cveoy.top/t/topic/hiNI 著作权归作者所有。请勿转载和采集!