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

            }

このコードについては詳しく説明しません。「rs」結果セットの最初のクエリから ID を取得しており、「servicearray」には Db に挿入したいサービスがありますが、この配列をどのように行うかループで時間がかかります。データベースへの一括挿入?

すぐにあなたからの連絡をお待ちしています

前もって感謝します

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 に答える