JDBC封裝工具類
1.配置文件(注意配置文件放在src目錄下
db.properties
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_exer?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
2.JDBCUtils實現類
JDBCUtils.java
package com.yang.util;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* @author WangYang
* @version 1.0
* @create 2020-02-27 9:09
*
* 分裝JDBC 工具類
*/
public class JDBCUtils {
private static Properties p;
static {
try {
//加載配置文件
p = new Properties();
p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
Class.forName(p.getProperty("driverName"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取Connection對象
* @return Connection對象
*/
public static Connection getConnection() {
try {
return DriverManager.getConnection(p.getProperty("url"),p.getProperty("username"),p.getProperty("password"));
} catch (SQLException e) {
System.err.println("獲取Connection連接失敗!");
e.printStackTrace();
}
return null;
}
/**
* 釋放資源方法
* @param rs 結果集對象
* @param st 語句對象
* @param conn 連接對象
*/
public static void close(ResultSet rs, Statement st, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}