public class DruidUtils {
private static DataSource ds;
static {
try {
Properties pro = new Properties();
pro.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void close(Connection conn, Statement stmt, ResultSet rs){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static DataSource getDataSource(){
return ds;
}
//修改参数的方法
//String sql:sql语句
//Object[] params:参数数组
public static int update(String sql,Object[] params){
Connection conn = null;
PreparedStatement pstmt = null;
try{
conn = getConnection();
pstmt = conn.prepareStatement(sql);
//获取到参数个数
ParameterMetaData md = pstmt.getParameterMetaData();
//参数的个数
int num = md.getParameterCount();
//将参数赋值给对应的?号
for (int i = 0; i < num; i++) {
pstmt.setObject(i+1,params[i]);
}
return pstmt.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
close(conn,pstmt,null);
}
return 0;
}
}