JDBC-編寫工具類

何時本身建立工具類

  • 若是一個功能常常要用到, 咱們建議把這個功能作成一個工具類, 能夠在不一樣的地方重用
  • 得到數據庫鏈接操做,將在之後的增刪改查全部功能中都存在.因此能夠封裝工具類JDBCUtils,提供獲取鏈接對象的方法, 從而達到代碼重複利用

JDBC工具類包含的內容

  • 自定義成員常量: 用戶名,密碼,URL,驅動類
  • 自定義成員方法getConnection()獲取鏈接
  • 關閉全部打開的資源

JDBCUtils示例代碼

public class JDBCUtils {

    private static final String DATABASE = "lianxi01";
    private static final String USER = "root";
    private static final String PASSWORD = "316426";
    private static final String URL = "jdbc:mysql://localhost:3306/" + DATABASE + "?characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";

    private static Connection conn = null;
    private static Statement sqlExecute = null;

    // a. 獲取鏈接
    public static Connection getConnection(){

        try {
            // 1. 註冊驅動
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 鏈接數據庫
            conn = DriverManager.getConnection(URL, USER, PASSWORD);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return conn;
    }

    // b. 獲取語句執行平臺 Statement對象
    public static Statement createStatement(Connection conn){

        // 3. 獲取語句執行平臺
        try {
            sqlExecute = conn.createStatement();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return sqlExecute;
    }

    // 3. 關閉流對象 --- 未執行查詢語句
    public static void close(Connection conn, Statement sqlExecute){

        try {
            if(null != sqlExecute) {
                sqlExecute.close();
            }
            if(null != conn) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    // 關閉流對象 --- 執行查詢語句 方法重載
    public static void close(Connection conn, Statement sqlExecute, ResultSet resultset){

        try {
            if(null != resultset) {
                resultset.close();
            }
            if(null != sqlExecute) {
                sqlExecute.close();
            }
            if(null != conn) {
                conn.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}
相關文章
相關標籤/搜索