用Java向資料庫中插入大量資料時的優化

2021-08-26 04:05:32 字數 1760 閱讀 7147

使用jdbc向資料庫插入100000條記錄,分別使用statement,preparedstatement,及preparedstatement+批處理3種方式進行測試: 

//1.使用statement插入100000條記錄 

public void exec(connection conn) 

//結束時間

long endtime = system.currenttimemillis();

system.out.println("st:"+(endtime-begintime)/1000+"秒");//計算時間

st.close();

conn.close();

} catch (sqlexception e)

}

//2.使用preparedstatement物件 

public void exec2(connection conn) 

conn.commit();

long endtime = system.currenttimemillis();

system.out.println("pst:"+(endtime-begintime)/1000+"秒");//計算時間

pst.close();

conn.close();

} catch (sqlexception e)

}

//3.使用preparedstatement + 批處理 

public void exec3(connection conn) 

}long endtime = system.currenttimemillis();

system.out.println("pst+batch:"+(endtime-begintime)/1000+"秒");

pst.close();

conn.close();

} catch (sqlexception e)

}

在oracle 10g中測試,結果: 

1.使用statement  耗時142秒; 

2.使用preparedstatement 耗時56秒; 

3.使用preparedstatement + 批處理耗時: 

a.50條插入一次,耗時5秒; 

b.100條插入一次,耗時2秒; 

c.1000條以上插入一次,耗時1秒; 

通過以上可以得出結論,在使用jdbc大批量插入資料時,明顯使用第三種方式(preparedstatement + 批處理)效能更優。

/*
普通方式處理大量資料的insert時,處理速度相當慢。

*/preparedstatement ps = null;

//迴圈10000次

for(int i = 0; i < 100000; i++)

/*

方法二:通過addbatch()的方式,將資料快取在物件裡面,通過最後執行executebatch();方法提交,因此速度會快很多!

*/preparedstatement ps = con.preparestatement(sql);

for(int i = 0; i < 100000; i++)

ps.executebatch();

向mysql資料庫下的某個表中插入大量資料

使用的方法 delimiter use macross wudi drop procedure if exists test create procedure test begin declare i int default 333 declare j int default 333 while i...

python向oracle資料庫中插入資料

安裝完成之後 import cx oracle conn cx oracle.connect 使用者名稱 密碼 資料庫名 連線資料庫 db conn.cursor 建立游標 d1 db.execute sql語句 執行完dql查詢語句 例如select 還需要呼叫乙個fetch方法來完成操作 tup...

java 向資料庫插入記錄

通過statement author administrator 介面statement 所有已知子介面 callablestatement,preparedstatement 一般使用這個 物件由connection.createstatement 建立 public class insert i...