package JDBC; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.Scanner; public class JDBCTest { //1.main方法 //2.判斷查詢方式輸入 1 根據ID查詢 2,根據名字查詢 //3.組成sql 語句 執行查詢 public void TestGetstudent() throws Exception{ //獲得查詢方式 int serchType = getSearchType(); students students = getSearchStudentType(serchType); prinStudents(students); } //打印學生信息 public void prinStudents(students students){ if (students != null) { System.out.println(students); } else { System.out.println("查無此人!"); } } private int getSearchType(){ //查詢的方式1,ID。 2 根據姓名查詢 System.out.println("請輸入查詢的方式:1 ID查詢 2 姓名查詢"); Scanner scanner = new Scanner(System.in); int type = scanner.nextInt(); if (type != 1&& type !=2 ){ System.out.println("輸入的代碼錯誤"); throw new RuntimeException(); } return type; } //判斷查詢的方式 private students getSearchStudentType(int type) throws Exception{ String sql = "SELECT * FROM students WHERE "; Scanner scanner = new Scanner(System.in); if (type==1){ System.out.println("請輸入學生的ID"); int exam = scanner.nextInt(); sql = sql+"id = '" + exam + "'"; System.out.println(sql); }else { System.out.println("請輸入學生的姓名"); String name = scanner.next(); sql = sql+"name = '" + name + "'"; System.out.println(sql); } //執行查詢 students students = getStudents(sql); return students; } private students getStudents(String sql) throws Exception{ students students = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try{ connection = JDBCTools.getConnection(); statement = connection.createStatement(); resultSet = statement.executeQuery(sql); if (resultSet.next()){ students = new students(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3)); } }catch (Exception e){ e.printStackTrace(); }finally { JDBCTools.release(resultSet, statement, connection); } return students; } }