public class JdbcUtils {
//加载properties类,只需要加载一次
static Properties props = new Properties();
//属性参数
private static Connection conn = null;
private static PreparedStatement pstmt = null;
//静态代码块直接执行加载驱动类
static{
try {
//加载src目录下的db.properties文件
props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
//加载驱动类
Class.forName(props.getProperty("driverClassName"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 得到连接对象
* @return Connection
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
conn = DriverManager.getConnection(props.getProperty("url"),props.getProperty("user"),props.getProperty("password"));
return conn;
}
/**
* 关闭资源 --倒序关闭
* @param rs 结果集
*/
public static void close(ResultSet rs){
try {
if(rs != null){
rs.close();
}
if(pstmt != null){
pstmt.close();
//还原初始值
pstmt = null;
}
if(conn != null){
conn.close();
//还原初始值
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 增删改方法
* @param sql sql语句
* @param params ?参数
* @return 受影响的函数
*/
public static int executeUpdate(String sql,Object...params){
try {
conn = JdbcUtils.getConnection();
//sql语句调用者传递
pstmt = conn.prepareStatement(sql);
//给参数赋值
if(params != null && params.length > 0){
for (int i = 0; i < params.length; i++) {
//pstat.setDate(parameterIndex, x); //需要的java.sql.Date
// 需要把java.util.Date 转换为java.sql.Date
// java.util.Date 是java.sql.Date的父类
// java.util.Date 赋值给java.sql.Date 把父类转换为子类 不能强制类型转换
//java.sql.Date的构造方法:
//Date(long date) 使用给定的毫秒时间值构造一个 Date对象。
//而java.util.Date 中long getTime() 获取当前时间的毫秒值
if(params[i] instanceof java.util.Date){
java.util.Date hiredate = (java.util.Date)params[i];
pstmt.setDate(i+1,new java.sql.Date(hiredate.getTime()));
}else{
pstmt.setObject(i+1, params[i]);
}
}
}
return pstmt.executeUpdate();
} catch (SQLException e) {
//e.printStackTrace();
//手动抛一个运行时异常给调用者
throw new RuntimeException(e);
}finally{
JdbcUtils.close(null);
}
}
/**
* 查询方法
* @param sql sql语句
* @param params ?参数
* @return 返回结果集
*/
public static ResultSet executeQuery(String sql,Object...params){
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
//sql语句由调用者提供
pstmt = conn.prepareStatement(sql);
//给参数赋值
if(params != null && params.length > 0){
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i+1, params[i]);
}
}
rs = pstmt.executeQuery();
return rs;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}