Insert data to database With Batch Update in Java
Description
The following code shows how to insert data to database With Batch Update.
Example
/* www . j av a2s .c o m*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Main {
public static void main(String[] argv) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctutorial",
"root", "root");
con.setAutoCommit(false);
String sql = "INSERT product VALUES(?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1, "A");
prest.setInt(2, 2002);
prest.addBatch();
prest.setString(1, "B");
prest.setInt(2, 1998);
prest.addBatch();
prest.setString(1, "C");
prest.setInt(2, 1980);
prest.addBatch();
prest.setString(1, "D");
prest.setInt(2, 1975);
prest.addBatch();
int count[] = prest.executeBatch();
con.commit();
con.close();
}
}