2014-05-13 83 views
2

我對此非常直截了當。即使在調用setString()之後,發送到準備好的語句的問號仍然是一個問號。這是爲什麼?JDBC中的問號佔位符和c3p0 PreparedStatement在setString()中未被替換

package com.orangeandbronze.buyfromus.dao; 


import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 

    import com.orangeandbronze.buyfromus.model.User; 
    import com.mchange.v2.c3p0.impl.NewProxyConnection; 

public class UserDaoPooled implements UserDao { 

@Override 
public User findByUsername(String username) throws DataAccessException{ 
    // TODO Auto-generated method stub 

    NewProxyConnection conn = (NewProxyConnection)ConnectionManager.getInstance().getConnection(); 
    StringBuilder queryBuilder = new StringBuilder(""); 
    queryBuilder.append("SELECT fld_username,fld_password,fld_role_type"); 
    queryBuilder.append("FROM tbl_user WHERE username= ? "); 
    queryBuilder.append("AND tbl_role.key_role=tbl_user.key_role"); 


    String query = queryBuilder.toString(); 

    try { 

     PreparedStatement stmt; 
     stmt = conn.prepareStatement(queryBuilder.toString()); 
     stmt.setString(1, username); 

     ResultSet rs = stmt.executeQuery(query); 

     rs.last();     //move to last row and get current position 
     int rowCount = rs.getRow(); 

     if(rowCount==1){ 

      return new User(rs.getString(1),rs.getString(2),rs.getString(3)); 
     } 

     else{ 

      return null; 
     } 

    }catch (SQLException e) { 

     throw new DataAccessException("Unable to connect to our database servers",e); 
    } 

} 

} 

回答

1

你已經設定在prepareStatement語句的查詢和綁定的變量 - 沒有必要在executeQuery,即再次提供它:

PreparedStatement stmt; 
stmt = conn.prepareStatement(queryBuilder.toString()); 
stmt.setString(1, username); 

ResultSet rs = stmt.executeQuery(); <-- No query 

這應該也意味着之前致電String query = queryBuilder.toString();也是多餘的,可以刪除。

+0

哇。我在那裏有很多混亂。謝謝先生。 – Jekk