MySQL資料庫的使用流程,代碼解釋

來源:互聯網
上載者:User

標籤:style   blog   io   color   ar   os   使用   sp   for   

資料庫的使用流程:
 1.註冊驅動;
 2.用DriverManager.getConnection方法獲得連線物件con;
 A方法:
   3.用連線物件的createStatement()方法,獲得可以執行sql語句的對象stmt;
   4.stmt執行查詢(查詢語句);
 B方法(推薦):
   3.用連線物件的prepareStatement方法,獲得帶參數(查詢語句)的預先處理對象pstmt;
   4.pstmt執行查詢,並將結果集賦予ResultSet對象;

 1 public class DbTest{ 2     public static void main(String[] args) {     3         /** 4          * 資料庫的使用: 5          * 1.註冊驅動; 6          * 2.用DriverManager.getConnection方法獲得連線物件con; 7          *     A方法: 8          *         3.用連線物件的createStatement()方法,獲得可以執行sql語句的對象stmt; 9          *         4.stmt執行查詢(查詢語句);10          *     B方法(推薦):11          *         3.用連線物件的prepareStatement方法,獲得帶參數(查詢語句)的預先處理對象pstmt;12          *         4.pstmt執行查詢,並將結果集賦予ResultSet對象;13          */14         try {15                 Class.forName("com.mysql.jdbc.Driver");                                                      //註冊驅動16                 Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/book","root","root123");//獲得連線物件17                 //使用statement方法處理sql語句的執行,與 PreparedStatement方法稍有不同。18                 Statement stmt=con.createStatement();                                     //獲得可以執行sql語句的對象19                 ResultSet rs=stmt.executeQuery("select * from bookinfo where id=1");            //執行查詢,並將結果集賦予ResultSet對象20                 /**推薦以下方法:21                 PreparedStatement pstmt=con.prepareStatement("select * from bookinfo where id=1");//獲得預先處理對象22                 ResultSet rs=pstmt.executeQuery();                                       //執行查詢,並將結果集賦予ResultSet對象23                  */24                 while(rs.next())25                 {int id=rs.getInt(1);26                     System.out.println(rs.getString(2)+"  "+rs.getString(3)+"  "+rs.getString(4));27                 }28             } catch (ClassNotFoundException e) {                                              //捕獲驅動類無法找到異常29                 e.printStackTrace();                                        30             } catch (SQLException e) {                                                            //捕獲SQL異常31                 e.printStackTrace();32             }33         }34 }

 

MySQL資料庫的使用流程,代碼解釋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.