java_JDBC
public abstract class DBCP_Utiles<T> {
/**
* 带有配置文件的DBCP的使用:
* <p>
* 核心类:BasicDataSourceFactory(工厂)
* public static DataSource createDataSource(new FileInputStream("xxx.properties"));
*/
// private static BasicDataSource ds=new BasicDataSource();
private static BasicDataSource ds = null;
static {
Properties ps = new Properties();
try {
//直接获取流的方式:工程根目录
// ps.load(new FileInputStream("dbcp.properties"));
//类加载器获取配置文件:src目录
ps.load(DBCP_Utiles01.class.getClassLoader().getResourceAsStream("dbcp.properties"));
ds = (BasicDataSource) BasicDataSourceFactory.createDataSource(ps);
} catch (Exception e) {
// TODO Auto-generated catch block
throw new RuntimeException("加载错误");
}
}
public static Connection getConnection() throws Exception {
return ds.getConnection();
}
public static void closePoor(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println(e);
}
}
}
//sql增删改
public int exec_update(String sql, Object[] params) throws Exception {
Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject((i + 1), params[i]);
}
int num = preparedStatement.executeUpdate();
return num;
}
//sql查询
public ArrayList<T> exec_query(String sql, Object[] params) throws Exception {
ArrayList<T> list = new ArrayList();
Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject((i + 1), params[i]);
}
}
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
T t = this.getBean(resultSet);
list.add(t);
}
return list;
}
//获取bean
public abstract T getBean(ResultSet rs) throws SQLException;
}