JDBC批處理及參數綁定.java

來源:互聯網
上載者:User
public   static   void  main(String[] args)  ... {
    Class.forName("sqldriver");
    Connection conn = DriverManager.getConnection(URL,USER,PASS)
    
    //無參,添加案例
    Statement stmt = conn.createStatement();
    stmt.addBatch("insert into authors(firstName,lastName) values('fegor','hack')");
    stmt.addBatch("insert into authors(firstName,lastName) values('fegors','hacks')");
    stmt.addBatch("insert into authors(firstName,lastName) values('fegorsr','hacksr')");
    stmt.executeBatch();
    stmt.close();
    conn.close();
    
    //帶參,添加案例
    PreparedStatement ps=conn.prepareStatement("insert into authors(firstName,lastName) values(?,?)");
    
    ps.setString(1,"nihao1");//設定參數
    ps.setString(2,"wohao1");
    ps.addBatch();           //把語句加入批處理隊列
    
    ps.setString(1,"nihao2");
    ps.setString(2,"wohao2");
    ps.addBatch();

    ps.setString(1,"nihao3");
    ps.setString(2,"wohao3");
    ps.addBatch();

    ps.executeBatch();        //執行批處理
    
    ps.close();               //最後關閉
    conn.close();
}
// 總結:
// 1.stmt=conn.createStatement()這個後面的括弧裡面一般沒有東西。。。
// 2.pstmt=conn.prepareStament("insert into authors(firstName,lastName) values(?,?)")
// 這個後面一定有sql語句,並且裡面的參數是用。表示的。
// 然後用pstmt.setString(1,"fegor")來設定它的值,1表示第1個問號的位置,"fegor",表示我們要加的值
// 最後用pstmt.executeUpdate()去執行。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.