database.properties
代碼如下:
jdbc.driver_class=oracle.jdbc.driver.OracleDriver
jdbc.connection.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.connection.username=scott
jdbc.connection.password=tiger
ConfigManager.java
代碼如下:
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
//讀取配置文件(屬性文件)的工具類
public class ConfigManager {
private static ConfigManager configManager;
// properties.load(inputStream);讀取屬性文件
private static Properties properties;
// 在構造工具類時,進行配置文件的讀取
private ConfigManager() {
String configFile = "database.properties";
properties = new Properties();
InputStream is = ConfigManager.class.getClassLoader()
.getResourceAsStream(configFile);
try {
// 讀取配置文件
properties.load(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 通過單例模式設置實例化個數
public static ConfigManager getInstance() {
if (configManager == null) {
configManager = new ConfigManager();
}
return configManager;
}
// 通過key獲取對應的value
public String getString(String key) {
return properties.getProperty(key);
}
}
BaseDao.java
代碼如下:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.book.util.ConfigManager;
//基類:數據庫操作通用類
public class BaseDao {
protected Connection conn;
protected PreparedStatement ps;
protected Statement stmt;
protected ResultSet rs;
// 獲取數據庫連接
public boolean getConnection() {
// // 讀取配置信息
String driver = ConfigManager.getInstance().getString(
"jdbc.driver_class");
String url = ConfigManager.getInstance().getString(
"jdbc.connection.url");
String username = ConfigManager.getInstance().getString(
"jdbc.connection.username");
String password = ConfigManager.getInstance().getString(
"jdbc.connection.password");
// 加載JDBC驅動
try {
Class.forName(driver);
// 與數據庫建立連接
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
return false;
} catch (SQLException e) {
return false;
}
return true;
}
// 增刪改的通用方法
public int executeUpdate(String sql, Object[] params) {
int updateRows = 0;
getConnection();
try {
ps = conn.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
System.out.println(i + 1 + "---" + params[i]);
}
System.out.println(sql);
updateRows = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return updateRows;
}
// 查詢
public ResultSet executeSQL(String sql, Object[] params) {
getConnection();
try {
ps = conn.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
// 關閉資源
public void closeAll(){
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}