根据上节DML的代码,我们将每次执行sql语句时重复的代码抽取出来
形成了一个静态代码块(注册驱动程序)和2个方法getConnection() – 用于获取连接,
close(Connection conn,Statement stmt) – 用于关闭连接资源
将其封装在一个类中,JdbcUtil工具类应声而出,代码如下:
/**
* jdbc工具类
*
* @author llj
*
*/
public class JdbcUtil {
private static String url = "jdbc:mysql://localhost:3306/day17";
private static String user = "root";
private static String password = "123";
/**
* 将注册驱动程序放在静态代码块中
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("jdbc驱动程序注册失败!");
}
}
/**
* 抽取获取连接对象的方法
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 释放资源的方法
*/
public static void close(Connection conn,Statement stmt){
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
用上面的工具类,我们写一个测试用例:
@Test
public void testInsert() {
Connection conn = null;
Statement stmt = null;
try {
conn = JdbcUtil.getConnection();
// 3.创建statment
stmt = conn.createStatement();
// 4.准备sql
String sql = "INSERT INTO student (NAME,gender)VALUES('齐八','女')";
// 5.执行sql语句,得到返回结果
int count = stmt.executeUpdate(sql);
// 6、获取返回结果
System.out.println("本次执行共影响了:" + count + "行数据");
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {// 7.关闭连接资源(注意顺序:后打开的先关闭)
JdbcUtil.close(conn, stmt);
}
}
就光看看代码长度,是不是已经简化了好多呢?(必须滴)