File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases 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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Prepared Statement problem" Watch "Prepared Statement problem" New topic

Prepared Statement problem

jim gemlo

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

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

Joined: May 26, 2003
Posts: 33132

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

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Shailesh Chandra
Ranch Hand

Joined: Aug 13, 2004
Posts: 1082

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
I agree. Here's the link:
subject: Prepared Statement problem
It's not a secret anymore!