文章目錄
- (一)jdbc查詢代碼
- (二)JDBC存在的問題:
- (三)解決方案:
(一)jdbc查詢代碼
下面這段jdbc查詢的代碼,想必每個學過javaweb的同學,都是經歷過的,
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加載資料庫驅動
Class.forName("com.mysql.jdbc.Driver");
// 通過驅動管理類獲取資料庫鏈接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "123456");
// 定義sql陳述句?表示占位符
String sql = "select * from user where username = ?";
// 獲取預處理statement
preparedStatement = connection.prepareStatement(sql);
// 設定引數,第?個引數為sql陳述句中引數的序號(從1開始),第?個引數為設定的引數值
preparedStatement.setString(1, "tom");
// 向資料庫發出sql執?查詢,查詢出結果集
resultSet = preparedStatement.executeQuery();
// 遍歷查詢結果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
// 封裝User
user.setId(id);
user.setUsername(username);
}
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 釋放資源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
} }
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
通過上面這段再熟悉不過的jdbc代碼,可以看到,使用再多的jdbc對資料庫做操作的時候,無非就這么幾個步驟:
- 1、加載資料庫驅動;
- 2、通過驅動管理類獲取資料鏈接;
- 3、自定義sql陳述句;
- 4、拿到sql陳述句,并執行;
- 5、拿到執行結果,
(二)JDBC存在的問題:
- 1、資料庫配置資訊、sql執行陳述句等,寫死在Java代碼中(存在硬編碼,不方便后期維護);
- 2、每一次執行sql都會創建一個鏈接,并釋放(浪費資源);
- 3、對最終執行的結果需要手動的去封裝回傳結果集,較為繁瑣,
(三)解決方案:
- 1、使用組態檔加載配置資訊;
- 2、使用連接池,資源不用了就放回去,等待下一個使用的人;
- 3、可以使用反射,對表的欄位和Java物體類的屬性做自動映射,
- 4、使用其他持久層框架,例如:Mybatis
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/275533.html
標籤:其他
下一篇:pgsql時間問題
