public class DBUtils {
static private Connection conn;
static private PreparedStatement pstmt;
static private ResultSet rs;
// 使用單例模式實現的數據庫Connection方法
static public Connection getConnection() {
try {
if (conn == null) {// 若是已經存在一個connection的實例化對象,則直接使用,避免大量建立多餘對象浪費系統資源
Properties properties = new Properties();// 實例化一個properties加載相應數據庫的配置信息
properties.load(DBUtils.class.getResourceAsStream("properties文件路徑"));
String driver = properties.getProperty("driverClassName");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Class.forName(driver);// 加載數據庫驅動
conn = DriverManager.getConnection(url, username, password);// 創建數據庫鏈接
}
return conn;
} catch (Exception e) {
System.out.println("鏈接數據庫不成功" + e.getMessage());
}
return null;
}
// 實現基本的數據庫增刪改操做
public int update(String sql, Object... obj) {
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);// 構建Statement查詢語句
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(1 + i, obj[i]);
}
int i = pstmt.executeUpdate();// 執行Statement語句
return i;// 返回操做影響響應表的行數
} catch (Exception e) {
System.out.println("更新數據失敗");
}
return 0;
}
// 實現數據庫的查詢操做,這裏以將查詢結果構形成一個Map鍵值對的形式並存入List線性表中爲例
public List<Map<String, Object>> query(String sql, Object... obj) {
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(1 + i, obj[i]);
}
rs = pstmt.executeQuery();
////////////////////////
ArrayList<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = rs.getMetaData();//得到數據庫中相應表結構
while (rs.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < metaData.getColumnCount(); i++) {
map.put(metaData.getColumnLabel(i + 1), rs.getObject(i + 1));
}
arrayList.add(map);
}
return arrayList;
///////////////////////
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
// 關閉數據庫鏈接,數據庫鏈接的關閉應該自低向上依次關閉
public void close() {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
} catch (Exception e) {
System.out.println("關閉失敗");
}
}
}