/**
- JDBC工具类 实例工具类
- 单例模式 饿汉
- @author 11561
*/
导包:
/**
* 私有化构造方法
*/
private JDBCUtil() {
// TODO Auto-generated constructor stub
}
/**私有化单例常量*/
private static final JDBCUtil INSTANCE = new JDBCUtil();
/**
* 公开静态方法获取单例工具类对象
* @return
*/
public static JDBCUtil getInstance() {
return INSTANCE;
}
/**
* 实例方法获取连接
* @return
* @throws SQLException
* @throws IOException
*/
public Connection getConnection() throws SQLException, IOException {
//获取配置文件
Properties properties = new Properties();
//通过当前线程对象获取类加载器再获取文件输入流和缓冲流
Thread currentThread = Thread.currentThread();
ClassLoader contextClassLoader = currentThread.getContextClassLoader();
//在source文件夹下的自动编译
InputStream resourceAsStream = contextClassLoader.getResourceAsStream("mysql.properties");
BufferedInputStream bufferedInputStream = new BufferedInputStream(resourceAsStream);
//读取配置文件信息创建连接
properties.load(bufferedInputStream);
//获取信息
String url = properties.getProperty("url");
String driverClass = properties.getProperty("driverClass");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
//获取连接
Connection connection = DriverManager.getConnection(url,user,password);
return connection;
}
/**
* 实例方法 释放资源
* @param statement
* @param connection
*/
public void close(Statement statement,Connection connection,ResultSet resultSet) {
try {
if (resultSet!= null) {
resultSet.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally {
if (connection != null) {
try {
connection.close();
} catch (Exception e2) {
// TODO: handle exception
e2.printStackTrace();
}
}
}
}
}