Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

preparedStatement

 
qionghua yang
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
My code starts here:

public void prepareSQLString(String whereString, String orderString)
{
String query = "SELECT * FROM uw_aplus_files WHERE c_uw_fil_sts = ? ORDER BY ?";
try
{
stmt = connection.prepareStatement(query);
stmt.setString(1, whereString);
stmt.setString(2, orderString);
}
catch (SQLException e)
{
System.out.println(e.toString());
System.exit(1);
}
I got the following error:
java.sql.SQLException: [INTERSOLV][ODBC Informix driver] [Informix]A syntax error has occurred.
Question: Can I use placeholder for order by?
Thanks!
qionghua
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No because you can only fill in ? with a value not a column name which is what the order by is looking for.
 
qhyang
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Thomas.

But then can I have any other method that can make the order by clause dynamically? I mean I can order by the field that I pass into the function so that it will order dynamically.
Thanks!
qionghua
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can build the SQL statement dynamically and then execute it.
orderBy = "col2";
sqlStatement = "select col1, col2 from table1 order by " + orderBy;
 
qionghua yang
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot , Thomas.
My code looks like this now. And it works alright.
public void prepareSQLString(String whereString, String orderString)
{
String query = "SELECT * FROM table WHERE field = ? ORDER BY " + orderString;
try
{
stmt = connection.prepareStatement(query);
stmt.setString(1, whereString);
}
catch (SQLException e)
{
System.out.println(e.toString());
System.exit(1);
}
}
qionghua
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great! Glad I could help!
------------------
Moderator of the JDBC Forum
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic