package com.cn.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class JdbcUtils { // database connection
static final String DRIVERCLASS;
static final String URL;
static final String USER;
static final String PASSWORD;
static {
// to require ResourceBundle,这里唯一想做笔记的就是下面的几行代码,直接读取src下的配置文件“jdbc.properties”,不要太简单。。这里记得不要加后缀名,还有就是我这种写法,配置文件是放在项目的src路径下,还有配置文件不要加逗号或者分号或者引号。。。key-value形式写完之后直接换行。。。
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
DRIVERCLASS = bundle.getString("driverClass");
URL = bundle.getString("url");
USER = bundle.getString("user");
PASSWORD = bundle.getString("password");
}
static {
// register the driving class
try {
Class.forName(DRIVERCLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// to require connection
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
// close connections,release resources
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
closeResultSet(rs);
closeStatement(st);
closeConn(conn);
}
// close the Connection
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
// close the Statement
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
}
// close the ResultSet
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
}