2012-04-16 52 views
0

您好,我是新來的Java,我使用循環從陣列需要時間,我怎麼會在數據庫中插入數據的批量插入我的代碼在這裏插入在數據庫,Java批量插入循環需要附加時間碼?

if(con != null) 
      { 

        rs = dboperation.DBselectstatement(con,"select host_object_id from nagios_hosts where address='"+ip+"'"); 

        if (rs != null) 
        { 
         rs.next(); 
         String id = rs.getString(1); 
         for(int i= 0;i<serviceArray.length;i++) 
         {   
         status.append(serviceArray[i]+"\n"); 
         dboperation.DbupdateStatement(DbAcess.getNagios_connection(),"insert into nagios_servicelist(service_name,host_object_id) values('"+serviceArray[i]+"','"+id+"')"); 
         } 
        } 

      } 

就不詳細去這段代碼我告訴你,我從「rs」結果集中的第一個查詢中獲得id,「servicearray」中有我想要在Db中插入的服務,但是它需要時間循環如何在數據庫中執行此數組批量插入操作?

希望從你很快就會聽提前

回答

2

您shuld使用JDBC批量插入你的目的

謝謝 -

//Create a new statement 
Statement st = con.createStatement(); 

//Add SQL statements to be executed 
st.addBatch("insert into nagios_servicelist(service_name,host_object_id) values('"+serviceArray[0]+"','"+id+"')"); 
st.addBatch("insert into nagios_servicelist(service_name,host_object_id) values('"+serviceArray[1]+"','"+id+"')"); 
st.addBatch("insert into nagios_servicelist(service_name,host_object_id) values('"+serviceArray[2]+"','"+id+"')"); 

// Execute the statements in batch 
st.executeBatch(); 

你可以在這裏插入自己的邏輯。但這是如何完成這一工作的概述。

+0

我有許多陣列價值觀,所以我將不得不使用循環您的代碼? – 2012-04-16 06:41:47

+0

是的,你必須使用循環。 – Pushkar 2012-04-16 06:43:54

+0

但如果我將使用循環,它會再次需要很長時間,因爲它正在我的代碼循環中? – 2012-04-16 06:50:34

1

下面的代碼避免了內存不足的錯誤以及SQL注入

String sql = "insert into employee (name, city, phone) values (?, ?, ?)"; 
Connection connection = new getConnection(); 
PreparedStatement ps = connection.prepareStatement(sql); 

final int batchSize = 1000; 
int count = 0; 

for (Employee employee: employees) { 

    ps.setString(1, employee.getName()); 
    ps.setString(2, employee.getCity()); 
    ps.setString(3, employee.getPhone()); 
    ps.addBatch(); 

    if(++count % batchSize == 0) { 
     ps.executeBatch(); 
    } 
} 
ps.executeBatch(); // insert remaining records 
ps.close(); 
connection.close();