0

HI everyone I was wondering if there is a specific way how you can execute multiple INSERT queries with minimum code so I don't repeat the INSERT procedure every time.

For example I'm doing a workout feature for a program and the way it works is a user can select 3 exercises for each muscle group and than I'm having a table in my database where I want to store what the user have selected.

I want to execute all of the inserts by clicking just one button.

Here you can see screenshot of my program for your illustration.

https://i.stack.imgur.com/GYBny.jpg

  • Use `addBatch` & `executeBatch` commands for executing multiple SQL statment. [Good Example](http://stackoverflow.com/questions/10929369/how-to-execute-muliple-sql-statements-from-java) – Suzon Apr 02 '14 at 17:12
  • Thanks, I will take a look at this as well and than decide whether I should use this or a loop like rrirower suggested. – user3058242 Apr 02 '14 at 17:14

2 Answers2

1

If you are using JDBC, you should check the addBatch method. Here is a good tutorial for efficient inserts: http://viralpatel.net/blogs/batch-insert-in-java-jdbc/

I would recommend the SQL injection safe mechanism.

Guy Bouallet
  • 2,099
  • 11
  • 16
0

Depending on how you structure your code, you should be able to construct a loop that collects the necessary data and dynamically creates the sql insert statement. In your example, the loop would execute three times, each time just changing the values of the columns to be inserted.

rrirower
  • 4,338
  • 4
  • 27
  • 45
  • Can you just explain a little more what do you mean by "dynamically creates the sql insert statement" – user3058242 Apr 02 '14 at 17:05
  • You can use [prepared statements](http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html) to accomplish that. – rrirower Apr 02 '14 at 17:09