JDBC的工具类提取
JDBC的工具类提取:
packagecom.luyue.jdbc;
importjava.io.IOException;
importjava.io.InputStream;
importjava.sql.*;
importjava.util.Properties;
public classJDBCUtils {
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
//使用动态加载资源文件的方式获取值,这样修改值只需要修改属性文件即可
//加载属性文件并解析
Properties prop = new Properties();
try {
//如何获得属性文件的输入流,通常用类的加载器方式
InputStream is =JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
prop.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driverClass =prop.getProperty("driverClass");
url =prop.getProperty("url");
username =prop.getProperty("username");
password =prop.getProperty("password");
}
private static void loadDriver() throwsClassNotFoundException {
Class.forName(driverClass);
}
public static Connection getConnection()throws SQLException {
Connection conn =DriverManager.getConnection(url, username, password);
return conn;
}
public static void relase(Statementstatement, Connection conn) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static void relase(ResultSetresultSet, Statement statement, Connection conn){
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}