3

I want to know which is a better approach of inserting multiple rows in database:

  1. Using one query to do this or
  2. for( int x = 0; x < y.length; x++ ) { insertRowsIntoDatabase( valuesHere ); }
  3. Or you guys have another approach? Please share.

My data is consist about 8 columns and 50 rows.

1
  • Why don't you run some timed test cases and see? Commented Nov 18, 2013 at 10:53

5 Answers 5

3

A better way would be to do a batch insert, instead of inserting rows 1 by 1.

for (String query : queries) {
    statement.addBatch(query);
}
statement.executeBatch();
Sign up to request clarification or add additional context in comments.

2 Comments

Is this better than the one query?
Performance wise, not very sure(because internally, even the single query, MAY insert that many times, as the no. of rows), but readability wise, it is definitely better.
2

You can use bulk insert

save all values in a txt file and use.

BULK INSERT STUDENT
FROM ‘D:\STUDENTS_LIST.txt’
WITH ( FIELDTERMINATOR = ‘,’, ROWTERMINATOR = ‘\n’ )

1 Comment

2

Always use one query when you can. This has multiple advantages:

  • Fewer connections to the DBMS, reducing the network access and other things done when you connect to the server (even if it's on the same computer as the program)
  • Better optimization of the query. The DBMS is better than you at optimizing. Always. Doing multiple queries will hinder the optimization process of the DBMS, even with caching systems.

Anyway, 8 columns and 50 rows is very fast and easy to handle for any DBMS, but your data may grow later, so you want to use the best approach.

Comments

2

yes you can write only one query to insert all values:

String query="insert into table1 (First,Last) values";
for(; ;)
{
    query=query+"('Fred','Smith'),";
}
 -----You can write your database insertion code here----

Or you can use addBatch() and executeBatch(); method also......

Plz refer this link for read more about addBatch() Method

Comments

1

Consider using a single Prepared Statement Batch, with multiple data sets as batch.

(Note: Not all JDBC drivers may support this and exactly follow the spec.)

Comments

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.