Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) 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.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!