public class JdbcUtils {
private static String DRIVER;
private static String URL;
private static String USERNAME;
private static String PASSWORD;
static {
ResourceBundle bindel = ResourceBundle.getBundle("db");
//读取配置文件中的配置信息
DRIVER = bindel.getString("driver");
URL = bindel.getString("url");
USERNAME = bindel.getString("username");
PASSWORD = bindel.getString("password");
}
/**
* 获取数据库连接方法
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
//注册驱动
Class.forName(DRIVER);
//获取连接
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭资源
* @param conn
* @param pstemt
* @param rs
*/
public static void CloseSql(Connection conn,PreparedStatement pstemt, ResultSet rs) {
if(conn != null ) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pstemt != null ) {
try {
pstemt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null ) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
db.properties配置文件信息为:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=utf-8
username=xxx
password=xxx