Alexander
Alexander

Reputation: 9

SQL INSERT with loop with multiple rows

I'm trying to insert skeleton data into a database using jdbc.

So far my code is:

   Statement st=con.createStatement();
   String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
                    + "VALUES (1, 1, 'forename1', 'surname1', '1996-06-03');";

I need to create 100 entries for this and I'm not too sure how to go about doing it. All I want is the student id, titleid, forename and familyname to increment by 1 until it reaches 100 entries with those rows filled in, date of birth doesn't need to be altered. I'm asking how to do a loop for this

Upvotes: 0

Views: 3213

Answers (2)

Dan Bracuk
Dan Bracuk

Reputation: 20804

There are two ways to do this. You can put your insert query inside a loop or you can put your loop inside an insert query. I have found that the better method depends on the database engine (but I've never used postresql) and the number of records you want to insert. You could bump up against the maximun query length or number of parameters or something.

The following code sample is ColdFusion, but it is intended to show the general idea of having a loop inside a query. You would have to write equivalent code in java.

<cfquery>
insert into yourtable
(field1
, field2
, etc)
select null
, null
, null
from SomeSmalllTable
where 1 = 2
<cfloop>
union
select <cfqueryparam value="#ValueForField1#">
, <cfqueryparam value="#ValueForField#">
, etc
</cfloop>
</cfquery>

Upvotes: 0

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

General answer - You should use PrepareStatement instead of Statement and execute as batch.

Common way to insert multiple entry or execute

String sql = "INSERT INTO student (studentid, titleid, forename, familyname, dateofbirth) "
                    + "VALUES (?, ?, ?, ?, ?);";
ps = connection.prepareStatement(SQL_INSERT);
for (int i = 0; i < entities.size(); i++) {
    ps.setString(1, entity.get...());
    ...
    ps.addBatch();
}
ps.executeBatch();

Important Note:

  1. Why you should use PrepareStatement Over Statement

  2. SQL Injection Example

Upvotes: 2

Related Questions