JDBC學習再小結

JDBC學習再小結

一、JDBC概念
 
二、JDBC常用四個核心對象
    DriverManager
        getConnection();
    Connection
        createStatement();
        prepareStatement();
    Statement(PreparedStatement)
        ResultSet executeQuery();
        int executeUpdate();
        boolean execute();
        delete from users where id = ? 
        ps.setInt(1, 5);
    ResultSet 
        next();
        getInt();
        getString();
        getDouble();
        getDate();
        ...
        
三、編寫一個java應用步驟:
    1、創建項目,添加jar包
    2、編寫操作數據庫的類
        try {
            // 加載驅動
            Class.forName("com.mysql.jdbc.Driver");
            // 創建連接Connection
            Connection conn = DriverManager.getConnection("jdbc:mysql:///day06","root","abc");
            // 獲取執行sql的statement對象
            // conn.createStatement();
            PreparedStatement ps = conn.prepareStatement("select * from users where id = ? and name = ?");
            ps.setInt(1, 5);
            ps.setString(2, "tom");
            // 執行語句,並返回結果
            ResultSet rs = ps.executeQuery();
            // 處理結果
            while (rs.next()) {
                User u = new User();
                u.setInt(rs.getInt("id"));
                u.setName(rs.getString("name"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //關閉資源
            if (rs != null)
                rs.close();
            if (ps != null)
                ps.close();
            if (conn != null)
                conn.close();
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章