Saturday, April 28, 2012

Execute a SQL Statement with Variable Parameters


When you need to execute the same SQL statement (in general an UPDATE) multiple times with different parameter values you can use the PrepareStatement method like this: 

Connection conn=null;
PreparedStatement pst=null;
String[] nm=new String[3];
int[] nc=new int[3];
...
try {
nm[0]="Costescu",nm[1]="Alexandrescu",nm[2]="Popovici";
nc[0]=234423;nc[1]=123344;nc[2]=534562;

pst=conn.prepareStatement("UPDATE Table1 SET Nume=? WHERE Nr_cont=?");
     for(int i=0;i<=2;i++)
         {
         pst.setString(1,nm[i]);
         pst.setInt(2,nc[i]);
         pst.executeUpdate();
         }
     }catch (SQLException e){System.out.println(e.getMessage());}

No comments:

Post a Comment