db.properties的配置文件
public class JdbcUtil {
static String driver;static String url;
static String user;
static String pwd;
//靜態方法
static {try {
// 通過類加載器來加載db.properties
InputStream inputStream = JdbcUtil.class.getClassLoader()
.getResourceAsStream("db.properties");
// 創建一個properties的實例
Properties properties = new Properties();
// 加載配置文件
properties.load(inputStream);
driver = properties.getProperty("jdbc.driver");url = properties.getProperty("jdbc.url");
user = properties.getProperty("jdbc.username");
pwd = properties.getProperty("jdbc.password");
Class.forName(driver);// 加載驅動類
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 創建mysql數據庫的連接
*/
public static Connection openConnection() throws SQLException {
return DriverManager.getConnection(url, user, pwd);
}
//關閉連接
public static void close(Connection conn) {if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement stmt) {
if (null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}