Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an Array of Characters into DB

Tags:

java

jdbc

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?

like image 209
nishanreads Avatar asked Jun 09 '26 12:06

nishanreads


2 Answers

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();
like image 142
Dmitri Avatar answered Jun 11 '26 02:06

Dmitri


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());
like image 39
tres2k Avatar answered Jun 11 '26 04:06

tres2k