通过JDBC链接数据库在获取链接和释放链接处代码的改进——通过配置文件传参
1.设置db.properties配置文件
- 书写时需要注意不能有多余的空格
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/web08?useUnicode=true&characterEncoding=utf8
username=root
password=123456
2.定义一个JDBCUtils_V2类,里面提供一个获取链接的方法和一个释放链接的方法
- 通过调用ResourceBundle.getBundle("db");的方法获得配置好的文件
- 通过调用ResourceBundle里面getString方法获得配置文件中的参数
public class JDBCUtils_V2 {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
ResourceBundle bundle = ResourceBundle.getBundle("db");
driver = bundle.getString("driver");
url = bundle.getString("url");
username = bundle.getString("username");
password = bundle.getString("password");
}
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return conn;
}
public static void release(Connection conn,PreparedStatement pstmt,ResultSet rs) {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(pstmt!=null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}