資料庫的批處理

來源:互聯網
上載者:User

package cn.Pdispose;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;


import cn.paging.JdbcUtil;


//批處理
public class Dispose {
private static Connection conn = null;
private static Statement st = null;
private static PreparedStatement ps = null;
public static void testInsert(){
try {
conn = JdbcUtil.getConnection();
st = conn.createStatement();
String sql1 = "insert into t_name(id,name) values(1,'jing')";
String sql2 = "insert into t_name(id,name) values(2,'zhang')";
String sql3 = "delete from t_name where id = 1";
//addBatch()內部為一個list,加到list中
st.addBatch(sql1);
st.addBatch(sql2);
st.addBatch(sql3);
//元素師每條語句影響到的行數
int [] i = st.executeBatch();
for(int num : i){
System.out.println(num);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.closeJdbc(conn, null, ps);
}
}

//同時在一個表裡邊插入100條資料
//由於語句完全相同,只是參數不同,使用PreparedStatement
public static void testInsert_1(){
long date = System.currentTimeMillis();
try {
conn = JdbcUtil.getConnection();
String sql = "insert into t_name values(?,?)";
ps = conn.prepareStatement(sql);
for(int i=1;i<=100;i++){
ps.setInt(1, i);
ps.setString(2, "date---"+i);
//將一組參數添加到此 PreparedStatement 對象的批處理命令中。
ps.addBatch();
}
//將一批命令提交給資料庫來執行,如果全部命令執行成功,則返回更新計數組成的數組。
ps.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.closeJdbc(conn, null, ps);
}
System.out.println("用時:"+((System.currentTimeMillis()-date)/1000)+"秒");
}

//想資料庫中插入10000條資料,並設定緩衝區
public static void testInsert_2(){
//初始化一個時間
long time = System.currentTimeMillis();
try {
conn = JdbcUtil.getConnection();
String sql = "insert into t_name values(?,?)";
ps = conn.prepareStatement(sql);
for(int i=1;i<1000001;i++){
ps.setInt(1, i);
ps.setString(2, "date"+i);
ps.addBatch();
if(i%1000==0){
ps.executeBatch();
ps.clearBatch();//清空資料
}
}
ps.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtil.closeJdbc(conn, null, ps);
}

System.out.println("用時:"+((System.currentTimeMillis()-time)/1000)+"秒");
}


public static void main(String[] args) {
testInsert_2();
}
}













相關文章

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.