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();
}
}
}