生活随笔
收集整理的這篇文章主要介紹了
jdbc万能dao
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
jdbc萬能dao
一,為何封裝萬能dao
- 不用框架,純jdbc連接數據庫,會用到dao包,如果每個表都要寫增刪改查,一個dao至少四個方法,dao會有大量代碼重復,所以封裝dao包,解決sql參數的問題。
- 提高代碼復用率
- 更好用,只要sql,和參數數組
二,代碼實現
package dao
;import java
.sql
.*
;
public class ToolDao {static {try {Class
.forName("oracle.jdbc.OracleDriver");} catch (ClassNotFoundException e
) {e
.printStackTrace();}}static Connection conn
= null
;static PreparedStatement ps
= null
;static ResultSet rs
= null
;public static Connection
getConn() throws SQLException
{String url
= "jdbc:oracle:thin:127.0.0.1:1521:orcl";conn
= DriverManager
.getConnection(url
, "scott", "scott");return conn
;}public static void closeAll() {try {if (rs
!= null
)rs
.close();if (ps
!= null
)ps
.close();if (conn
!= null
)conn
.close();} catch (SQLException e
) {e
.printStackTrace();}} public int executeUpdate(String sql
, Object
[] objs
) {int i
= -1;try {conn
= getConn();ps
= conn
.prepareStatement(sql
);if (objs
!= null
) {for (int j
= 0; j
< objs
.length
; j
++) {ps
.setObject(j
+ 1, objs
[j
]);}i
= ps
.executeUpdate();}} catch (SQLException e
) {e
.printStackTrace();} finally {closeAll();}return i
;}public ResultSet
executeQuery(String sql
, Object
[] objs
) {try {conn
= getConn();ps
= conn
.prepareStatement(sql
);if (objs
!= null
) {for (int j
= 0; j
< objs
.length
; j
++) {ps
.setObject(j
+ 1, objs
[j
]);}}rs
= ps
.executeQuery();} catch (SQLException e
) {e
.printStackTrace();} finally {}return rs
;}}
總結
以上是生活随笔為你收集整理的jdbc万能dao的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。