简体   繁体   中英

How to use a place holder for preparestatement to bind a variable for table name

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?

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 .

他们将表名视为字符串,您可以使用强制类型转换。

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); // 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM