JdbcUtils类:
package com.itheima.utils;
import java.sql.*;
import java.util.ResourceBundle;
public class JdbcUtils {
static final String DRIVERCLASS;
static final String URL;
static final String USER;
static final String PASSWORD;
static {
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
DRIVERCLASS = bundle.getString("driverClass");
URL = bundle.getString("url");
USER = bundle.getString("user");
PASSWORD = bundle.getString("password");
}
static {
try {
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
/**
* 释放资源
*
* @param conn 连接
* @param st 语句执行者
* @param rs 结果集
*/
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
closeResultSet(rs);
closeStatement(st);
closeConn(conn);
}
/**
* 释放连接
*
* @param conn 连接
*/
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
/**
* 释放语句执行者
*
* @param st 语句执行者
*/
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
}
/**
* 释放结果集
*
* @param rs 结果集
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
}
配置文件(jdbc.properties)
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/day07
user=root
password=123
测试类(Hello.java):
@Test
public void f3() {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
conn = JdbcUtils.getConnection();
String sql = "insert into category values(?,?)";
st = conn.prepareStatement(sql);
st.setString(1, "c006");
st.setString(2, "户外2");
int i = st.executeUpdate();
if (i == 1) {
System.out.println("success");
} else {
System.out.println("error");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.closeResource(conn, st, rs);
}
}