jdbc鏈結資料庫進行增刪改查時,會出現許多冗餘比較強,不夠美觀的**。對**進行合理的封裝不僅利於檢視,更對執行速度有很大的提公升。
本片文章以插入操作為例,簡單介紹了資料庫操作時一些簡單的封裝,如果大家有更好的意見或建議,歡迎在討論區交流。
題目:我要往員工表裡面插入一名員工資料,這名員工有以下屬性:
name, idcard, gender, age, birth, profession, telephone, state
person person =
newperson
(name, idcard, gender, age, birth, profession, telephone, state)
;
問題:假如我直接將學生的這些值作為引數去生成sql語句,那麼就會造成資料冗餘,並且**看起來特別不整齊。還不利於sql語句的編寫。
解決:將這些資訊封裝成乙個陣列物件,採取動態傳參的形式,生成sql語句,進行資料庫操作
//要插入的物件
person person =
newperson
(name, idcard, gender, age, birth, profession, telephone, state)
;//將物件的資訊採用陣列存起來。
object[
] obj =
;//呼叫生成sql語句的方法
boolean complete =serviceimpl.
insertperson
(obj)
;
//sql語句生成方法 這裡採用了動態傳參
public
boolean
insertperson
(object.
..obj)
//進行資料庫操作
public
boolean
insertperson
(string sql, object.
.. obj)
int result = pstmt.
executeupdate()
;if(result >0)
else
}catch
(sqlexception e)
finally
return
false
;}
//關閉資料庫訪問方法的封裝
utilityc3p0類
public
static
void
closeall
(autocloseable.
..closeables)
catch
(exception e)}}
}
autocloseable介面是乙個釋放資料庫資源的方法,主要用於資源管理,在資料庫釋放資源方面可以減少許多**的復用。 JDBC訪問資料庫的步驟
1.裝載驅動程式 class.forname sun.jdbc.odbc.jdbcodbcdriver 使用jdbc odbc裝載驅動程式 class.forname com.mysql.jdbc.driver 使用mysql的驅動程式 class.forname com.microsoft.jdb...
JDBC訪問資料庫七個步驟
以連線mysql資料庫為例,其他的資料庫都差不多,如下 1 建立sql語句 string sql 2 註冊驅動 class.forname string drivername 3 建立連線 connection con drivermanager.getconnection string url,s...
JDBC資料庫連線步驟
1 載入資料庫驅動 class.forname com.mysql.jdbc.driver 2 建立資料庫連線池 conn drivermanager.getconnection jdbc mysql localhost 3306 test2?user root password 1234 3 由當...