JdbcUtil 工具类
public class JdbcUtil {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClass = null;
static{
try {
/**
* 读取jdbc.properties
*/
//1)创建Properties对象
Properties prop = new Properties();
//构造输入流
Class clazz = JdbcUtil.class;
InputStream in = clazz.getResourceAsStream("/jdbc.properties");
//加载文件
prop.load(in);
//读取
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
driverClass = prop.getProperty("driverClass");
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取连接方法
*/
public static Connection getConnection(){
try {
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
/**
* 释放资源方法
*/
public static void close(ResultSet rs,PreparedStatement ptmt,Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
if(ptmt!=null){
try {
ptmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
public static void close(PreparedStatement ptmt,Connection conn){
if(ptmt!=null){
try {
ptmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}
}
Jdbc.properties
url=jdbc\:mysql\://localhost\:3306/数据库名
user=root
password=123456
driverClass=com.mysql.jdbc.Driver
对更新操作进行封装
/**
* 封装增加删除修改的通用工具方法
* @param sql SQL语句
* @param objs SQL语句占位符实参,如果没有参数则传入null
* @return 返回增删改的结果,返回类型为int
*/
public static int executeDML(String sql,Object...objs){
// 声明jdbc变量
Connection conn = null;
PreparedStatement ps = null;
int i = -1;
try {
// 获取连接对象
conn = DBUtil.getConnection();
// 开启事务管理
conn.setAutoCommit(false);
// 创建SQL命令对象
ps = conn.prepareStatement(sql);
// 给占位符赋值
if(objs!=null){
for(int j=0;j<objs.length;j++){
ps.setObject(j+1,objs[j]);
}
}
// 执行SQL
i = ps.executeUpdate();
conn.commit();
} catch (Exception e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
DBUtil.closeAll(null, ps, conn);
}
return i;
}