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

Passing Table Names in PreparedStatement

 
Senthil Kumar
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I was trying to pass a table name in the query dynamically like

query = "select * from ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1,"table1");

It Throws an Exception
"Exception in thread "main" com.sybase.jdbc3.jdbc.SybSQLException: ASA Error -141: Table '@p0' not found"

Is there a way to pass the table name dynamically?
Thanks in Advance
 
Prem Shankar
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Senthil,
We cannot pass tables as bind variable using prepared statement..
Instead form the query string dynamically.
eg: query="select * from "+var1;
 
Anubhav Anand
Ranch Hand
Posts: 341
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well we can't pass the tablename directly to prepared statements.

But, if you want to use stored procedures then you can pass table name dynamically using Dynamic SQL.

For further reading of Dynamic SQL refer this article on Dynamic SQL.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic