做這個小項目少不了與數據庫的關聯,為了避免多次重復代碼,封裝一個專門與數據庫進行交互的數據庫工具類。該類并不是要一步到位的完善好,而是在編碼的過程中逐漸發現怎樣封裝更好更方便去使用而逐步的完善
目前部分代碼如下,有需要的時候在進行更新:
DBUtil類進行數據庫連接,使用讀取文件的方式來確定數據庫,而不是在代碼中寫死,所以
private static Properties dbProps = new Properties();
用這個文件來保存相應數據庫的信息,同時寫一個靜態代碼塊,在加載這個類的時候加載JDBC并且讀取該文件
static {
try {
InputStream is = DBUtil.class.getResourceAsStream("/dbinfo.properties");
dbProps.load(is);
Class.forName(dbProps.getProperty("db.driver"));
} catch (Exception e) {
e.printStackTrace();
}
}
使用數據庫最多的就是增刪改查,使用到的基本的類:
Connection PreparedStatement ResultSet
增刪改的差別在sql語句,所以“增刪改”可以寫成一個方法,“查”單獨寫成一個方法
1:獲得Connection
public static Connection getCon() {
try {
return DriverManager.getConnection(
dbProps.getProperty("db.connectUrl"),
dbProps.getProperty("db.user"),
dbProps.getProperty("db.pwd"));
}catch(Exception e) {
e.printStackTrace();
return null;
}
}
2:查詢全部信息,傳入sql語句和一個實體類
利用java的反射技術,實例化一個類,并且從數據庫中查詢數據并挨個進行賦值,最終添加進一個List里面,但是List里面的元素類型是Object,使用的時候進行強制類型轉換即可
/**
* 查詢全部信息
* @param sql 寫明要查詢的表即可
* @param cls 傳入一個實體類,信息會存進這個實體類中
* @return 返回一個傳入實體類的數組
*/
public static List<Object> findAll(String sql, Class cls){
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<Object> list = new ArrayList<Object>();
try{
con = getCon();
pstm = con.prepareStatement(sql);
ResultSetMetaData rsmd = pstm.getMetaData();
int size = rsmd.getColumnCount();
rs = pstm.executeQuery();
while(rs.next()){
Object obj = cls.newInstance();
for(int i = 0 ; i < size ; i++){
Field f = cls.getDeclaredField(rsmd.getColumnName(i+1));
f.setAccessible(true);
f.set(obj, rs.getObject(i+1));
}
list.add(obj);
}
return list;
}catch(Exception e){
e.printStackTrace();
return null;
}finally{
close(rs, pstm, con);
}
}
3:更新操作即對數據庫的增刪改
傳入的sql語句和sql語句中占位符所需要的數據的一個數組
在方法中填充成完整的sql語句,然后執行
注:Statement 和 PreparedStatement 不同
Statement使用字符串連接,PreparedStatement可以使用?做占位符,防止SQL注入
public static int executeUpdate(String sql, Object[] params){
Connection con = null;
PreparedStatement pstm = null;
try{
con = getCon();
pstm = con.prepareStatement(sql);
if(params != null && params.length > 0){
for(int i = 0 ; i < params.length ; i++){
pstm.setObject(i+1, params[i]);
}
}
return pstm.executeUpdate();
}catch(Exception e){
e.printStackTrace();
return -1;
}finally{
close(null, pstm, con);
}
}
4:使用完后要進行close操作
public static void close(ResultSet rs, PreparedStatement pstm, Connection con) {
try {
if(rs!=null)
rs.close();
if(pstm!=null)
pstm.close();
if(con!=null)
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
這是目前所主要用到的方法,如有需要還會有添加和優化