2012-09-03 71 views
0

我有這樣的事情在我的sql查詢SQL準備好的語句不採用'?'在where子句

private static final String QUERY_PHYSICIAN_INFO= "SELECT * FROM PHYSICIAN_INFO WHERE ? = ?"; 

,但以下情況不工作雙方..

Connection conn = null; 
    PreparedStatement stmt = null; 
    String logintype; 
     if(isInteger(id)) 
     { 
      logintype="BADGEID"; 

     }else{ 
      logintype="ID"; 
     } 
     stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO); 
     stmt.setString(1, logintype); 
     stmt.setString(2, id); 
     ResultSet rs = stmt.executeQuery(); 
     Physician phs = null; 

對此有什麼特殊原因嗎? 在此先感謝。

回答

2

?用於傳遞參數,而不是字段名稱。

如果你必須這樣做,構建SQL作爲

"SELECT * FROM PHYSICIAN_INFO WHERE " + "BADGEID" + " = ?" 
+0

非常感謝您的關注,我試過這種方式,但它是靜態SQL查詢更新爲空。字符串logintype; String query =「SELECT * FROM PHYSICIAN_INFO WHERE」+ logintype +「=?」現在在某些方法中,我更新logintype爲其他值,最後生成的查詢是SELECT * FROM PHYSICIAN_INFO WHERE null =? – user1065490

+0

您需要更改SQL字符串,一旦您確定了什麼logintype是 – podiluska

0

你可以嘗試這樣的事情,因爲?只能用於傳遞參數,或者可以使用數據庫函數,然後將值傳遞給函數。

private static final String QUERY_PHYSICIAN_INFO_BADGE= "SELECT * FROM PHYSICIAN_INFO WHERE BADGEID = ?"; 

private static final String QUERY_PHYSICIAN_INFO_ID= "SELECT * FROM PHYSICIAN_INFO WHERE ID = ?"; 

Connection conn = null; 
    PreparedStatement stmt = null; 
    String logintype; 
     if(isInteger(id)) 
     {    
      stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO_BADGE); 

     }else{    
      stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO_ID); 
     } 
     stmt.setString(1, id); 
     ResultSet rs = stmt.executeQuery(); 
     Physician phs = null;