简体   繁体   中英

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM