当我必须插入100个非常相似的行时,使用PreparedStatement的最佳方法是什么?

Eas*_*onk 1 java mysql jdbc

我必须**inserts 100s of rows**进入数据库,例如除了一个列之外的所有列值完全相同.例如,考虑一个表

------------------
|UserId|Timestamp|
------------------ 
Run Code Online (Sandbox Code Playgroud)

现在**only timestamp is changing for every insert**.

以下列方式使用准备好的声明是否可取?

PreparedStatement pstmt = con.prepareStatement("INSERT INTO Pings (UserId,Timestamp) VALUES (?,?)"; 

pstmt.setInt(1,001); //setting user is 
while(true){
   pstmt.setTimestamp(2,getTimestamp());
   pstmt.executeUpdate(); 
}
Run Code Online (Sandbox Code Playgroud)

相比

while(true){
   pstmt.setInt(1,001);
   pstmt.setTimestamp(2,getTimestamp());
   pstmt.executeUpdate(); 
}
Run Code Online (Sandbox Code Playgroud)

鉴于我只设置第一列值一次,是否会首先接近工作?

Ell*_*sch 5

我建议你用PreparedStatement.addBatch()和批处理Statement.executeBatch().这可能看起来像,

int count = 0;
while (true) {
    pstmt.setInt(1, 001);
    pstmt.setTimestamp(2, getTimestamp());
    pstmt.addBatch();
    if (++count % 50 == 0) { // <-- batch size of 50.
        pstmt.executeBatch();
    }
}
pstmt.executeBatch();
Run Code Online (Sandbox Code Playgroud)