結果集
要建立一個 ResultSet
,你應該建立一個 Statement
或 PrepapredStatement
:
使用 Statement 建立 ResultSet
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/databasename", "username", "password");
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("SELECT * FROM my_table");
} catch (ClassNotFoundException | SQLException e) {
}
使用 PrepapredStatement 建立 ResultSet
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(
"jdbc:somedb://localhost/databasename", "username", "password");
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM my_table");
ResultSet result = preparedStatement.executeQuery();
} catch (ClassNotFoundException | SQLException e) {
}
檢查 ResultSet 是否包含資訊
if (result.next()) {
//yes result not empty
}
從 ResultSet 獲取資訊
你可以從 ResultSet
獲得幾種型別的資訊,例如 String, int, boolean, float, Blob
,…獲取你必須使用迴圈或簡單資訊的資訊:
if (result.next()) {
//get int from your result set
result.getInt("id");
//get string from your result set
result.getString("username");
//get boolean from your result set
result.getBoolean("validation");
//get double from your result set
result.getDouble("price");
}