Reputation: 55
I'm working on a SOAP based webservice where in a part of it i have to perform some queries on the database using nested loop, the problem is that the inner loop just gets executed for ONE time only, before giving up.This is the code:
for(int i=0; i<selec.length; i++){
for(int j=0; j<sintom.length;j++){
var[(i*sintom.length)+j] = "INSERT INTO malattia (nome, eta, descrizione, sesso, etnia, sintomi) "
+ "VALUES ('" + malattia + "','" + eta + "','" + descrizione + "','" + sexarra[0] + "','" + selec[i] + "','" + sintom[j] + "')";
}
}
This is where the queries are supposed to get executed:
if (errore.equals("")) {
try {
Statement st = conn.createStatement();
for(int i=0; i<selec.length; i++){
for(int j=0;j<sintom.length;j++){
st.executeUpdate(var[(i*sintom.length)+j]);}}
What happens is that no matter the size of select it will work fine as long as the length of sintom is 1,bigger than 1 and it wont work.
Thanks for your expert advices, always appreciated!
Upvotes: 0
Views: 468
Reputation: 440
Try to use PreparedStatement and its Batch capability instead of plain query to simplify code and prevent SQL-injection.
Upvotes: 1
Reputation: 691755
Your use-case is a perfect example of a case where a prepared statement should be used. Read more about them in the JDBC tutorial.
Using a prepared statement would allow
So, the code should look like this:
PreparedStatement ps = conn.prepareStatement("INSERT INTO malattia (nome, eta, ...) values (?, ?, ...)");
for (int i= 0; ...) {
for (int j = 0; ...) {
ps.setString(1, malattia);
ps.setString(2, eta);
...
ps.executeUpdate();
}
}
Upvotes: 1