实现通用的增删改操作
配置文件 jdbc.properties
user=root
password=123456
url=jdbc:mysql://localhost:3306/test?rewriteBatchedStatements=true
driverClass=com.mysql.jdbc.Driver
JDBCUtils
/**
*
* @Description 操作数据库的工具类
* @author shkstart Email:shkstart@126.com
* @version
* @date 上午9:10:02
*
*/
public class JDBCUtils {
/**
*
* @Description 获取数据库的连接
* @author shkstart
* @date 上午9:11:23
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
// 1.读取配置文件中的4个基本信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
// 2.加载驱动
Class.forName(driverClass);
// 3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
/**
*
* @Description 关闭连接和Statement的操作
* @author shkstart
* @date 上午9:12:40
* @param conn
* @param ps
*/
public static void closeResource(Connection conn,Statement ps){
try {
if(ps != null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
* @Description 关闭所有的资源操作
* @author shkstart
* @date 上午10:21:15
* @param conn
* @param ps
* @param rs
*/
public static void closeResource(Connection conn,Statement ps,ResultSet rs){
try {
if(ps != null)
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
实现通用的增删改操作类
public class PreparedStatementUpdateTest {
@Test
public void testCommonUpdate(){
// String sql = "delete from customers where id = ?";
// update(sql,3);
//order是关键字,所以需要在order两边加上 ` `
String sql = "update `order` set order_name = ? where order_id = ?";
update(sql,"FF","2");
}
//通用的增删改操作
public void update(String sql,Object ...args){//sql中占位符的个数与可变形参的长度相同!
Connection conn = null;
PreparedStatement ps = null;
try {
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句,返回PreparedStatement的实例
ps = conn.prepareStatement(sql);
//3.填充占位符
for(int i = 0;i < args.length;i++){
ps.setObject(i + 1, args[i]);//小心参数声明错误!!
}
//4.执行
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
//5.资源的关闭
JDBCUtils.closeResource(conn, ps);
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/45fa34927cd2551303b6919baf5c8e45.png)
![](https://i-blog.csdnimg.cn/blog_migrate/98e6af250b52a5051068e7b0fd677c53.png)
![](https://i-blog.csdnimg.cn/blog_migrate/2d8bfcaced909df1cfbfe2bf3957df0b.png)