0

嗨,我是 java 新手,我正在使用来自数组的循环插入到数据库中,这需要时间我将如何在 DB 中插入数据作为批量插入我的代码,

  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+"')");
                       }
                    }

            }

不要详细介绍这段代码在数据库中批量插入?

希望很快能听到你的声音

提前致谢

4

2 回答 2

2

您应该为您的目的使用 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();

您可以在此处插入自己的逻辑。但这是如何完成的概述。

于 2012-04-16T06:37:56.483 回答
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();
于 2012-06-06T20:10:32.313 回答