如何通過SQL查詢有效地從列中通過java有效獲取所有值,而無需在每次後續調用時連接到數據庫?檢索列中的所有值
我現在擁有的一切:
private List<String> retrieveSQLQuery(String sqlQuery) throws SQLException {
JDBC jdbc = new JDBC();
ResultSet rs = jdbc.getResultsSet(sqlQuery);
List<String> values = new ArrayList<>();
while (rs.next()) {
values.add(rs.getString("model"));
}
return values;
}
然而,其後每rs.next()
,它連接到數據庫,創建了一個聲明,然後檢索值。
它看起來像這樣:
Connecting to database... Creating statement... Statement Created. Connecting to database... Creating statement... Statement Created. value1 Connecting to database... Creating statement... Statement Created. Connecting to database... Creating statement... Statement Created. value2 Connecting to database... Creating statement... Statement Created. Connecting to database... Creating statement... Statement Created. value3
有沒有更有效的方式來做到這一點?
編輯:
這裏是我的ResultSet方法:
public ResultSet getResultsSet(String QueryString) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
CachedRowSetImpl crs = null;
try {
// STEP 1: Register JDBC driver
Class.forName(jdbcDriver);
// STEP 2: Open a connection
logger.info("Connecting to database...");
conn = DriverManager.getConnection(dbUrl, user, password);
// STEP 3: Execute a query.
logger.info("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = QueryString;
rs = stmt.executeQuery(sql);
crs = new CachedRowSetImpl();
crs.populate(rs);
logger.info("Statement Created.");
// STEP 5: Clean-up environment
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
} catch (SQLException e) {
logger.error(e.getMessage());
} finally {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
logger.error(e.getMessage());
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
logger.error(e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
logger.error(e.getMessage());
}
} // end try
return crs;
}
你應該創建一個簡單的,自包含的,可編譯示例http://sscce.org/。例如,我們不知道類型'JDBC'及其方法'getResultsSet()',因此很難知道什麼是錯誤的。從表中獲取特定列的常用方法是查詢選擇該列。 –
@LewBloch現在就去編輯。 – Robben
@LewBloch如果您需要更多信息,請讓我知道 – Robben