Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Shorten PreparedStatement lines

Status
Not open for further replies.

dreampolice

Technical User
Dec 20, 2006
85
US
I have a PreparedStatement with alot of values to insert into an Oracle Database.
Anyway to shorten the setString lines in a loop or any other way to shorten this??

Code:
  //Database connection part here
  //......
  private PreparedStatement stmt;

  public void houseMethod(BeanInfo theObject)
  {
        stmt = connection.prepareStatement("Insert into MainTable (house, zipcode, city, county, phone, mortgage, tax, insurance, state, land) values (?,?,?,?,?,?,?,?,?,?)");
        stmt.setString(1, theObject.getHouse());
        stmt.setString(2, theObject.getZipcode());
        stmt.setString(3, theObject.getCity());
        stmt.setString(4, theObject.getCounty());
        stmt.setString(5, theObject.getPhone());
        stmt.setString(6, theObject.getMortgage());
        stmt.setString(7, theObject.getTax());
        stmt.setString(8, theObject.getInsurance());
        stmt.setString(9, theObject.getState());
        stmt.setString(10, theObject.getLand());
        stmt.executeUpdate();
   }
 
If your parameters are only strings then you could pass a string array or a collection


//Database connection part here
//......
private PreparedStatement stmt;

public void houseMethod(Vector<String> theObject)
{
stmt = connection.prepareStatement("Insert into MainTable (house, zipcode, city, county, phone, mortgage, tax, insurance, state, land) values (?,?,?,?,?,?,?,?,?,?)");
int index = 1;
for(String field : theObject) {
stmt.setString(index++, field);
}
stmt.executeUpdate();
}
 
I'm with stefan: the shorter, the harder to read and maintain.

Cheers,
Dian
 
Yes, Stefan's reply is much better than mine. To save just a couple of lines of code, but by doing so making it harder to read and to maintain is not a good idea.
 
Thanks for all the messages! I will follow all the advise and not shorten it.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top