1. 程式人生 > 資料庫 >【每日Java】基於JDBC結構優化和資料庫連線池的工具類封裝

【每日Java】基於JDBC結構優化和資料庫連線池的工具類封裝

1、傳統JDBC7步驟:

public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/productsystem?useUnicode=true&character=utf-8";//指定連線的資料庫地址
        //時資料庫地址為jdbc:mysql:(協議名)//localhost(伺服器的地址在本地主機):3306(資料庫埠號)/productsystem(庫名)
        //?useUnnicode=true&character=utf-8 (?)是傳遞引數的關鍵字,傳遞的引數為可以使用Unnicode編碼和字元格式為UTF-8

        String user = "root";//使用者名稱
        String password = "";
        try {
            //1.註冊驅動,載入Driver類
            Class.forName("com.mysql.jdbc.Driver");//執行類載入
            //2.獲取連線物件
            Connection con = DriverManager.getConnection(url,user,password);
            System.out.println("連線成功");
            //3.編寫sql
            String sql = "select * from t_product limit 0,4";
            //String sql = "insert into t_product (product_name,price,product_type_id) values('巨集碁記筆記本旗艦版',5000.00,6)";
            //4.宣告sql的執行者
            Statement state = con.createStatement();
            //5.執行sql語句,返回受影響的行數
            ResultSet rs = state.executeQuery(sql);
            while(rs.next()) {//判斷當前指標指向的行是否非空(預設指向表中第一行)
                //類似於迭代器中的hasNext()方法
                int id = rs.getInt("id");
                String name = rs.getString("product_name");
                double price = rs.getDouble("price");
                int type = rs.getInt("product_type_id");
                System.out.println(id+" "+name+" "+price+" "+type);
                //get方法在迴圈語句中時僅返回值,在迴圈語句末尾則返回值後將指標移向下一行
                //類似於迭代器中的next()方法
            }
            //6.列印執行結果
            //System.out.println(rows);
            //關閉資源
            state.close();
            con.close();
        }
        catch (SQLException e) {
                e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
                e.printStackTrace();
        }
    }

2、優化:

①訪問資料庫設定連線資訊的步驟是可以封裝的,且使用者應該可以從本地修改此連線資訊。

②連線資料庫和關閉資源的步驟是可以封裝的。

③對資料庫進行查詢操作和更新操作是可以封裝的。

注意:只有sql語句根據系統需求而定,不同方法不一樣,無法封裝。

經過封裝後,JDBC7步驟被簡化為兩步,即JDBC的作用,編寫一個sql語句,並執行它獲得它從資料庫中得到的返回值。

3、封裝

封裝圖:

封裝包與工具類:

原始碼實現:

①訪問資料庫設定連線資訊的步驟是可以封裝的,且使用者應該可以從本地修改此連線資訊。

本地檔案,放在src目錄中。

②連線資料庫和關閉資源的步驟是可以封裝的。

③對資料庫進行查詢操作和更新操作是可以封裝的。