我只需要第二組眼睛就可以看到這個錯誤。插入不起作用,我看不出爲什麼。這是爲了做家庭作業。適用的代碼位於CustomerDAO類中。這是針對使用Stripes框架使用Java構建的Web應用程序。這裏是違規代碼:SQL佔位符將不會綁定
public void create(Customer customer) {
String sql = "insert into customer (`firstname`, `lastname`, `email`, " +
"`username`, `password`) values (?, ?, ?, ?, ?)";
try {
PreparedStatement sth = this.dbh.getCon().prepareStatement(sql);
sth.setString(1, customer.getFirstName());
sth.setString(2, customer.getLastName());
sth.setString(3, customer.getEmailAddress());
sth.setString(4, customer.getUserName());
sth.setString(5, customer.getPassword());
sth.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();;
} catch (NullPointerException ex) {
ex.printStackTrace();
} finally {
this.dbh.closeConnection();
}
}
正如我所說這種方法駐留在我的DAO。從註冊表單的動作bean調用此方法。以下是我測試過的東西:
客戶對象不爲空。客戶領域正在從表格中獲取他們的價值,他們是正確的。 DAO不爲空。數據庫已連接。
我通過測試Action Bean中的條件來檢查上述條目,如果條件爲真則返回null,否則我返回RedirectResolution。
我做了五條將變量綁定到SQL的行,並將SQL中的變量替換爲我想要插入的實際數據並將記錄插入。這就是爲什麼我相信這個問題是在這五行的地方:
sth.setString(1, customer.getFirstName());
sth.setString(2, customer.getLastName());
sth.setString(3, customer.getEmailAddress());
sth.setString(4, customer.getUserName());
sth.setString(5, customer.getPassword());
當我用這個,如果在動作豆我被重定向到一個完全空白頁面是怎麼知道的價值觀也必然聲明模型的字段。
if (this.customer.getFirstName().equals("Tony")) {
return null;
}
這裏是從動作豆submit方法:
public Resolution submit() {
this.customer = this.getCustomer();
this.customerDao = this.getCustomerDao();
this.customerDao.create(customer);
return new RedirectResolution(RegisterFormActionBean.class);
}
爲字段值的試驗this.customer = this.getCustomer();
下插入。我在所有表單字段上獨立運行該測試,並始終將其轉發到空白頁面。運行時,我被重定向回註冊頁面,但未插入記錄。我檢查了文檔,以確保setString()
方法是正確的,它似乎是。
我知道這可能是愚蠢的,我可以忽略,但我只是在這裏旋轉我的輪子。
實際問題:爲什麼當我將值硬編碼到SQL中時插入工作,但是當我將值綁定到語句時,插入無效。
你不需要這些反引號表名。他們是否造成了「SQLException」? – jlordo
你已經描述了一個問題,但至今沒有提出問題(更不用說具體的可回答的問題)。你的問題是什麼? –
什麼是錯誤/異常? –