JDBC之工具類封裝
編寫工具類步驟
1、將固定字符串定義爲常量
2、由於工具類的方法都是靜態,因此註冊驅動可以放在靜態代碼塊中
3、提供獲取連接對象的方法Connection getConnection();
4、提供關閉資源的方法close(ResultSet rs,Statement stmt,Connection conn);
5、重載關閉資源方法close(Statement stmt,Connection conn);
public class JDBCUtils {
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/day18";
private static final String JDBC_USER = "root";
private static final String JDBC_PASSWORD = "root";
//靜態代碼塊,在類加載時只會執行一次
static{
//註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
//返回連接對象
try {
return DriverManager.getConnection(JDBC_URL,JDBC_USER,JDBC_PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
// return null;
}
//關閉資源
public static void close(ResultSet rs, Statement stmt, Connection conn){
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//重載關閉資源
public static void close(Statement stmt,Connection conn){
close(null,stmt,conn);
}
}
更多免費技術資料可關注:annalin1203