I want to insert a 2 dimensional array into a DB table. Is there any way to insert these values into DB with a single INSERT statement rather than using multiple INSERT statements? These multiple statements create a tendency for DB connection pool issues and can create a latency in the application.
String[][] a = new String[10][2];
for(int i =0;i<10;i++)
{
st.executeUpdate("Insert into sap_details VALUES a[i][0],a[i][1]);
}
What happens here is there are effectively 10 INSERT statements being called for each row. I don't want it to; it should happen with only one INSERT statement.
Is there any way to do that?
Use JDBC Batch Updates? Using prepared statements should also help.
String[][] a = new String[10][2];
PreparedStatement pst = con.prepareStatement("INSERT INTO sap_details VALUES (?,?)");
for (int i = 0; i < 10; i++) {
pst.setString(1, a[i][0]);
pst.setString(2, a[i][1]);
pst.addBatch();
}
int[] results = pst.executeBatch();
With MySQL, something like this should do the trick, perfectly fine , Oracle won't like it. This feature is supported by DB2, SQL Server (since version 10.0 - i.e. 2008), PostgreSQL (since version 8.2), MySQL, and H2.
String[][] a = new String[10][2];
StringBuilder sb = new StringBuilder("Insert into sap_details (a,b) VALUES ");
for(int i =0;i<a.length;i++){
sb.append("(\'");
sb.append(a[i][0]);
sb.append("\',\'");
sb.append(a[i][1]);
sb.append("\')");
if(i < a.length -1 )
sb.append(",");
}
st.executeUpdate(sb.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With