JSP(Java Server Pages)是一種動態網頁開發技術,而MySQL是最流行的開源關系型數據庫管理系統,這篇文章將介紹如何使用JSP和MySQL實現一個選課系統。
設計數據庫
CREATE TABLE course ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, teacher VARCHAR(255) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE student ( id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, PRIMARY KEY (id) ); CREATE TABLE student_course ( student_id INT(11) NOT NULL, course_id INT(11) NOT NULL, FOREIGN KEY (student_id) REFERENCES student(id), FOREIGN KEY (course_id) REFERENCES course(id) );
連接數據庫
Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
查詢課程列表
String sql = "SELECT id, name, teacher FROM course"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String teacher = rs.getString("teacher"); out.println(id + " " + name + " " + teacher + " "); out.println("<a href='selectCourse.jsp?id=" + id + "'>選課</a>"); } rs.close(); ps.close(); conn.close();
選課頁面
String sql = "INSERT INTO student_course (student_id, course_id) VALUES (?, ?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, studentId); ps.setInt(2, courseId); ps.executeUpdate(); ps.close(); conn.close();
通過以上代碼實現了一個基本的選課系統,希望這篇文章對你有所幫助。