dbhelper
原创
©著作权归作者所有:来自51CTO博客作者ifubing的原创作品,请联系作者获取转载授权,否则将追究法律责任
抄写
package tools;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DbHelper {
// 配置数据的容器
public static final Properties PROPERTIES = new Properties();
// 加载驱动
static {
// 获得配置流数据
InputStream is = DbHelper.class.getResourceAsStream("config.properties");
// 容器读取流数据
try {
PROPERTIES.load(is);
} catch (IOException e) {
e.printStackTrace();
}
// 加载驱动
try {
Class.forName(PROPERTIES.getProperty("driver"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() {
// 读取配置中的数据
String url = PROPERTIES.getProperty("url");
String user = PROPERTIES.getProperty("user");
String pwd = PROPERTIES.getProperty("pwd");
// 获得连接对象
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, pwd);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
// 返回连接对象
return connection;
}
// 释放资源
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet) {
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}