0

I have a problem with a prepareStatement. I am trying to build a query to select the count but table names are different and the code is like this:

String sql = "SELECT COUNT(0) AS CNT FROM ? WHERE STUD_NM <> 'ABC' ";

String tableName;

for (int i = 0; i < studCode.size(); i++) {

    count = 0;

    tableName = "";  

    pstmt = con.prepareStatement(sql);

    pstmt.setString( 1 , "S_"+studCode.get(i));

   Syso(pstmt); // 

}

Query is prepared like,

"SELECT COUNT(0) AS CNT FROM 'S_HUBRECORD' WHERE STUD_NM <> 'ABC'"

Why does it append single quotes to table name?

Matthias
  • 3,582
  • 2
  • 30
  • 41
AmolKumar
  • 223
  • 1
  • 2
  • 5

3 Answers3

1

You can't. You need to construct your query with string concatenation. PreparedStatement is for field values, not for table name. The reason it's wrapping quotes around it is also because you used setString.

David Xu
  • 5,555
  • 3
  • 28
  • 50
0

They treat table name as a string you use type casting may be it work.

Aniket
  • 173
  • 12
0

You should do like this,

for (int i = 0; i < studCode.size(); i++) {

    String sql = "SELECT COUNT(0) AS CNT FROM "+"S_"+studCode.get(i)+" WHERE STUD_NM <> 'ABC' ";
    count = 0;

    pstmt = con.prepareStatement(sql);

    Syso(pstmt); // 

}
AmolKumar
  • 223
  • 1
  • 2
  • 5
Sridhar DD
  • 1,972
  • 1
  • 10
  • 17
  • it works. but can i prepare a query outside of for loop? – AmolKumar Jan 06 '15 at 06:52
  • The table name will change for each iteration means how will you move it out? – Sridhar DD Jan 06 '15 at 06:54
  • if i write code like, String sql = "SELECT COUNT(0) AS CNT FROM "+"S_"? WHERE STUD_NM <> 'ABC' "; for (int i = 0; i < studCode.size(); i++) { count = 0; pstmt = con.prepareStatement(sql); pstmt.setString(1,studCode.size()) Syso(pstmt); // } this prepare query correctly but the problem is that it append single quote to the table name. – AmolKumar Jan 06 '15 at 07:00
  • Thats what we are saying. You can't do that. because prepare statement sees ? like a column value so if it string it appends Single Quote. So if you surely want is out side then You can also use search and replace strategy. – Sridhar DD Jan 06 '15 at 07:06