今天要把我們之前輸入進table的資料作成表格輸出,也新增了幾段程式碼如下
(一)
System.out.println("請輸入查詢範圍(n1~n2)");
System.out.println("n1: ");
int selectNumber = sc.nextInt();
sc.nextLine();
while (selectNumber <= 0) {
System.out.println("輸入錯誤,n1必須大於0");
selectNumber = sc.nextInt();
}
System.out.println("n2: ");
int selectNumber2 = sc.nextInt();
sc.nextLine();
while (selectNumber2 < selectNumber) {
System.out.println("輸入錯誤,n2必須大於等於n1");
selectNumber2 = sc.nextInt();
}
queryData(selectNumber, selectNumber2);
(二)
public static void queryData(int selectNumber, int selectNumber2) {
String selectSQL = "SELECT * FROM student_information where number >= ? and number <= ? ";
try (Connection connection = DriverManager.getConnection(JDBC_url, JDBC_user, JDBC_password);
PreparedStatement preparedStatement = connection.prepareStatement(selectSQL)) {
preparedStatement.setInt(1, selectNumber);
preparedStatement.setInt(2, selectNumber2);
ResultSet resultSet = preparedStatement.executeQuery();
System.out.println("+--------+--------+--------+--------+");
System.out.println("| Number | Name | Gender | Age |");
System.out.println("+--------+--------+--------+--------+");
boolean hasData = false;
while (resultSet.next()) {
int queriedNumber = resultSet.getInt("number");
String name = resultSet.getString("name");
String gender = resultSet.getString("gender");
int age = resultSet.getInt("age");
System.out.printf("| %6d | %-6s | %-6s | %6d |%n", queriedNumber, name, gender, age);
hasData = true;
}
if (!hasData) {
System.out.println("No data found for student numbers less than: " + selectNumber);
}
System.out.println("+--------+--------+--------+--------+");
} catch (SQLException e) {
e.printStackTrace();
}
}
這段queryData可以查詢之前輸入過,存在資料庫裡的每筆資料,並把他輸出成一個表格,
(?因為我資料都亂打,都是一些邪門的東西,所以他會看起來很不整齊)
查詢的範圍是第一個區塊所設定的(n1,n2),並且還有偵測資料範圍的功能,來看看實際操作的成果
首先是正常的輸入
再來是如果範圍輸入錯誤