2016-04-05 155 views
0

我试图在我的类CreditCardDaoImpl上运行JUnit测试(CreditcardDAOTest)。我不断收到错误"java.sql.SQLException: No value specified for parameter 2",但我不认为有两个参数。 任何援助将不胜感激。我相信错误来自"ps.setLong(1, customerID);"我假设应该有一个"ps.setLong(x,x);"但我不知道它应该是什么。我尝试调试,它似乎应该是我的声明的名称条目:SQL JDBC和Java JUnit测试失败

final static String retrieveForCustomerID = 
     "SELECT name = ?, cc_number = ?, exp_date = ?, security_code = ?, WHERE customerID = ?;"; 

但我再次不确定。请知道我一直在试图弄清楚这一点,我只是在寻找指导。

//Method in CreditCardDAOImpl 
public CreditCard retrieveForCustomerID(Connection connection, Long customerID) throws SQLException, DAOException 
{ 
    if (customerID == null) 
    { 
     throw new DAOException("Trying to retrieve credit card with NULL customerID"); 
    } 

    PreparedStatement ps = null; 
    try 
    { 
     ps = connection.prepareStatement(retrieveForCustomerID); 
     ps.setLong(1, customerID); 
     ResultSet rs = ps.executeQuery(); 
     CreditCard cc = new CreditCard(); 
     cc.setName(rs.getString("name")); 
     cc.setCcNumber(rs.getString("cc_number")); 
     cc.setExpDate(rs.getString("exp_date")); 
     cc.setSecurityCode(rs.getString("security_code")); 
     return cc; 
    } 
    finally 
    { 
    } 
} 

//Method in CreditCardDAOTest 
@Test 
public void testRetrieveForCustomerID() throws Exception 
{ 
    DataSource ds = DataSourceManager.getDataSource(); 
    Connection connection = ds.getConnection(); 
    CreditCardDAO dao = new CreditCardDaoImpl(); 

    CreditCard ccard = dao.retrieveForCustomerID(connection, customerID); 
    assertNotNull(ccard); 
    assertNotNull(ccard.getCcNumber()); 
    assertNotNull(ccard.getExpDate()); 
    assertNotNull(ccard.getName()); 
    assertNotNull(ccard.getSecurityCode()); 

    connection.close(); 
} 
+0

你的意思是if(!rs.next()){ \t \t \t return null; \t \t} – user3512367

+0

第一个更改是按照以下方式更新您的查询,然后再使用resultSet作为rs.getXXX()调用rs.next()。这[链接](http://alvinalexander.com/blog/post/jdbc/jdbc-preparedstatement-select-like)应该有帮助 –

+0

太棒了!谢谢! – user3512367

回答

0

使用rs.next()和您的查询应该像

final static String retrieveForCustomerID = 
     "SELECT name, cc_number, exp_date, security_code from TABLE_NAME WHERE customerID = ?" 

注:与实际的表名上面的查询替换TABLE_NAME

0
  1. 我认为你应该在你的查询中指定你的表名并删除选择块中的问号。

    SELECT name, cc_number , exp_date, security_code FROM your_table_name WHERE customerID = ? 
    
  2. 在执行您的查询之前,您应该发送所有的详细信息?在查询中使用

    ps.setInt(), ps.setLong(), ps.setString().... etc. 
    
  3. 执行事先准备好的声明后得到的结果集,你应该使用

    rs.next() 
    

迭代你resutset。