3

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?

2 Answers 2

5

Use JDBC Batch Updates? Using prepared statements should also help.

Example

    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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot ! I think that should help me get away with any issues that may arise out of Connection pool issues / Deadlock or any DB issues arising out if multiple INSERT statements.
1

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());

3 Comments

It really is best to avoid hand-rolled SQL strings, if at all possible.
With User Input you can't control, I definitely would go with prepared statements. But I kind of like this style.
Thanks, but i am using Oracle DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.