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; } }
转载于:https://my.oschina.net/u/3554714/blog/2709408