JDBC中的问号占位符和c3p0 PreparedStatement未在setString()中替换

时间:2014-05-13 04:08:52

标签: java c3p0

我对此非常直截了当。即使在调用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 个答案:

答案 0 :(得分:1)

您已经在prepareStatement语句中设置了查询并绑定了变量 - 无需在executeQuery中再次提供该信息,即:

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

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

这也意味着前面对String query = queryBuilder.toString();的调用也是多余的,可以删除。