2016-04-05 229 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。