aspose file tools*
The moose likes JDBC and the fly likes Prepared Statement problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Prepared Statement problem" Watch "Prepared Statement problem" New topic
Author

Prepared Statement problem

jim gemlo
Greenhorn

Joined: Feb 24, 2004
Posts: 20
I am trying to use a prepared statment with variables in the sql string and cant get it to work. I can get it to work if I do it like this

This will remove the value from the selected row as required. But when I try to pass two values, a string and a variable it doesnt work. I do not get any error from the code either.


Any Ideas?

[ September 27, 2004: Message edited by: jim gemlo ]
[ September 27, 2004: Message edited by: jim gemlo ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I'd guess you can't dynamically set the column name that way. The point of the prepared statement is that the database can take time to optimize the statement and use the optimized version over and over. If you go changing column names it can't be sure the optimization is still good.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Moving this to the JDBC forum...


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30764
    
156

Stan is correct. You can only substitute values in a prepared statements. Not field names or table names.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Shailesh Chandra
Ranch Hand

Joined: Aug 13, 2004
Posts: 1081

instead of adding column name dynamically in prepared statement add it in your sql query. Then make prepared statememen and use like

StringBuffer sbSqlUpdateServerFact = new StringBuffer("UPDATE dbo.SERVER_FACT SET bkup_key = null WHERE ").append(" srvr_fact_key or your variable to hold column name ").append("= ?");

PreparedStatement stmtUpdateSrvrFact = conn.prepareStatement(sbSqlUpdateServerFact.toString());

stmtUpdateSrvrFact.setString(1, srvr_fact_key);//variable used to hold vaule

desired valuestmtUpdateSrvrFact.executeUpdate


Gravitation cannot be held responsible for people falling in love ~ Albert Einstein
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Prepared Statement problem