package T3; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class StudentJDBCDemo { public static void main(String[] args) throws ClassNotFoundException, SQLException { StudentJDBCDemo demo = new StudentJDBCDemo(); Student student = demo.findStudentById(3); System.out.println(student.toString()); } // 通過id查詢學生 public Student findStudentById(int id) throws ClassNotFoundException, SQLException { // 1.注冊數據庫驅動 Class.forName("com.mysql.cj.jdbc.Driver"); // 2.與數據庫建立連接 Connection conn = DriverManager.getConnection( "jdbc:mysql://@localhost:3306/student", "root", "123456"); // 3.創建用來執行SQL語句的Statement對象 Statement stmt = conn.createStatement(); // 4.執行SQL語句 String sql = "select id,name,sno,sex,birthday,cno"+ " from t_student"+ " where id="+id; ResultSet rs = stmt.executeQuery(sql); // 5.處理結果集 Student student = null; if(rs.next()) { student = new Student( rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4), rs.getDate(5), rs.getInt(6)); } // 6.釋放資源 if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } return student; } }