1. jdbcInfos.properties表(存放mysql数据库驱动和用户信息):
2. DBUtils工具类实现:
1. 调用getConn()方法时加载静态代码块 ,
完成注册驱动, 登录数据库, 并返回一个Connection对象
2. close()方法利用方法重载机制, 实现将jabc各个对象关闭的操作
package com.ujn.jdbcUtils;
import java.io.FileReader;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class DBUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* 调用静态方法时加载静态代码块
*/
static {
try {
Properties ppts = new Properties();
ClassLoader clr = DBUtils.class.getClassLoader();//clr类加载器对象
URL res = clr.getResource("jdbcInfos.properties");
String path = res.getPath();
//System.out.println(path);
ppts.load(new FileReader(path));//加载文件
url = ppts.getProperty("url_test_database");
user = ppts.getProperty("user");
password = ppts.getProperty("password");
driver = ppts.getProperty("driver");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
* @return Connection对象
* @throws Exception
*/
public static Connection getConn() throws Exception{
return DriverManager.getConnection(url, user, password);
}
/**
* 关闭数据库对象资源
* @param stat Statement对象
* @param conn Connection对象
*/
public static void close(Statement stat, Connection conn){
if (stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭数据库对象资源
* @param res ResultSet对象
* @param stat Statement对象
* @param conn Connection对象
*/
public static void close(ResultSet res, Statement stat, Connection conn){
if (res != null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭数据库对象资源
* @param res ResultSet对象
* @param pstat PreparedStatement对象
* @param conn Connection对象
*/
public static void close(ResultSet res, PreparedStatement pstat, Connection conn){
if (res != null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstat != null){
try {
pstat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭数据库对象资源
* @param pstat PreparedStatement对象
* @param conn Connection对象
*/
public static void close(PreparedStatement pstat, Connection conn){
if (pstat != null){
try {
pstat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}