java實現sql語句批處理

來源:互聯網
上載者:User

標籤:style   blog   io   os   ar   java   for   資料   div   

Statement實現批處理:

優點:能夠處理多種不同結構的sql語句

缺點:不能預先處理,執行效率較差。對於參數不同的同一條sql語句需要多次調用addBatch()

package com.itheima.batch;import java.sql.Connection;import java.sql.Statement;import org.junit.Test;import com.itheima.util.DBUtil;public class StatementBatch {/*mysql資料庫: create database batch; use batch; create table mybatch( id int primary key auto_increment, name varchar(50) ); insert into mybatch values (null, '1'); insert into mybatch values (null, '2'); insert into mybatch values (null, '3'); insert into mybatch values (null, '4'); */@Testpublic void statementBatch() {Connection conn = null;Statement stat = null;try{conn = DBUtil.getConn();stat = conn.createStatement();stat.addBatch("create database batch");stat.addBatch("use batch");stat.addBatch("create table mybatch( id int primary key auto_increment, name varchar(50) )");stat.addBatch("insert into mybatch values (null, '1')");stat.addBatch("insert into mybatch values (null, '2')");stat.addBatch("insert into mybatch values (null, '3')");stat.addBatch("insert into mybatch values (null, '4')");stat.executeBatch();} catch (Exception e) {e.printStackTrace();} finally {DBUtil.close(conn, stat, null);}}}

PreparedStatement實現批處理:

優點:能夠預先處理,執行效率高;參數不同的同一條sql語句執行簡便

缺點:只能批處理參數不同的同一條sql語句

package com.itheima.batch;import java.sql.Connection;import java.sql.PreparedStatement;import org.junit.Test;import com.itheima.util.DBUtil;public class PrepBatch {@Testpublic void prepBatch() {Connection conn = null;PreparedStatement ps = null;try{conn = DBUtil.getConn();ps = conn.prepareStatement("insert into mybatch value(null, ?)");for(int i = 0; i < 1000; i++) {ps.setString(1, "name" + i);ps.addBatch();}ps.executeBatch();} catch (Exception e) {e.printStackTrace();} finally {DBUtil.close(conn, ps, null);}}}



java實現sql語句批處理

相關文章

聯繫我們

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