封装工具类
为了减少代码工作量,将JDBC注册、获取连接、释放连接封装为一个工具类;
具体代码如下:
public class JDBCUtils {
//定义成员变量
private static DataSource ds;
static{
try {
//加载配置文件
Properties pro = new Properties();
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
//获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//释放资源
public static void close(Statement stmt,Connection conn){
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn){
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//获取连接池方法
public static DataSource getDataSource(){
return ds;
}
}
调用工具类
调用工具类具体实例如下:
public class DruidDemo2 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
//获取连接
conn = JDBCUtils.getConnection();
//定义sql
String sql = "insert into account values(null,?,?)";
//获取pstmt对象
pstmt = conn.prepareStatement(sql);
//给?赋值
pstmt.setString(1,"王五");
pstmt.setDouble(2,3000);
//执行sql
int count = pstmt.executeUpdate();
System.out.println(count);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//释放资源
JDBCUtils.close(pstmt,conn);
}
}
}