JDBC操作數據庫的七個基本步驟

  1. 使用反射方式加載驅動器

    Class.forName("com.mysql.jdbc.Driver");
  2. 創建連接數據庫對象

    String url = "jdbc:mysql://localhost[127.0.0.1]:3306/表名?characterEncoding=utf-8"
    String userName = "用戶名";
    String passWord = "密碼";
    Connection conn = DriverManage.getConnection(url,userName,PassWord);
  3. 創建操作數據庫對象

    Statement stat = conn.createStatement() || conn.prepareStatement();
  4. 創建Sql語句

    String sql = "select * from 表名 where 【約束條件】";
    String sql = "insert into 表名 列名 = 值 where 【約束條件】";
    String sql = "delete from 表名 where 【約束條件】";
    String sql = "update 表名 set 列名 = 值 where 【約束條件】"
  5. 執行Sql語句,並創建結果集

    ResultSet rs = stat.executeQuery() || stat.executeUpdate();
  6. 操作結果集

    while(rs.next()){
        rs.getString() || rs.getInt() || rs.getDouble() || rs.getFloat || rs.getDate()
    }
  7. 釋放資源

    //先創建的後釋放
    if(rs != null) rs.close();          //釋放結果集對象
    if(stat != null) stat.close();      //釋放操作數據庫對象
    if(conn != null) conn.close();      //釋放連接數據庫對象
  8. 增加:Create 讀取查詢:Retrieve 更新:update 刪除:delete

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章