2014-04-12 83 views
0

請給我建議!我在servlet中獲取表單數據並嘗試更新數據庫,但它不起作用。有數據庫連接(沒有servlet代碼,任何數據都正確地添加到數據庫中),但沒有任何異常被拋出。 servlet獲取參數 - 通過EL表達式在JSP中可用。我試圖通過聲明更新數據庫,而不使用preparedStatement,但它沒有幫助。這是代碼:無法通過表單數據更新數據庫

public class ServletClass extends HttpServlet { 
    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     DBConn dbConn = new DBConn(); 
     String number = req.getParameter("number"); 
     String amount = req.getParameter("amount"); 
     String date = req.getParameter("date"); 

     ArrayList list = dbConn.returnList(number, amount, date); 
     req.setAttribute("attr", list); 
     RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp"); 
     requestDispatcher.forward(req, resp); 
    } 
} 


public class DBConn { 

    public ArrayList<InvoicesBean> returnList(String number, String amount, String date) { 
     Connection connection = null; 
     Statement statement = null; 
     ResultSet resultSet = null; 
     ArrayList<InvoicesBean> beanList = new ArrayList<InvoicesBean>(); 
     PreparedStatement preparedStatement = null; 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved", "root", "1111"); 
      statement = connection.createStatement(); 
      preparedStatement = connection.prepareStatement("insert into invoices values(?, ?, ?);"); 
      preparedStatement.setString(1, number); 
      preparedStatement.setString(2, amount); 
      preparedStatement.setString(3, date); 
      preparedStatement.executeUpdate(); 
      resultSet = statement.executeQuery("SELECT * FROM invoices;"); 
      while (resultSet.next()){ 
       InvoicesBean invoicesBean = new InvoicesBean(); 
       invoicesBean.setNumber(resultSet.getString("number")); 
       invoicesBean.setAmount(resultSet.getString("amount")); 
       invoicesBean.setDate(resultSet.getString("date")); 
       beanList.add(invoicesBean); 
      } 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (resultSet != null) resultSet.close(); 
       if (statement != null) statement.close(); 
       if (connection != null) connection.close(); 
      } catch (SQLException e) { 
       e.printStackTrace(); 
      } 
     } 
     return beanList; 
    } 
} 

InvoiceBean級僅僅是一個標準的bean類的getter/setter方法

+0

您是否使用mysql客戶端檢查日期是否插入到數據庫中?也調試你的代碼,並檢查結果集是否有任何價值,也許問題是你的jsp上沒有顯示數據 – fmodos

+0

是的,數據通過mysql命令行插入,如果我從std java類更新表。 ResulSet有值 - 我也檢查過它。 – aime

回答

0
invoicesBean.setNumber(resultSet.getString("number")); 
      invoicesBean.setAmount(resultSet.getString("amount")); 
      invoicesBean.setDate(resultSet.getString("date")); 

你不能有數據庫列名作爲「數字」或「日期」。他們被保留。 再次檢查列名稱。 檢查這是否是錯誤,您可以用列號1,2,3替換列名稱。

+0

謝謝。是的,這很好。我發現最好使用列數)但真正的問題是在IDE(IntellijIDEA)中。它沒有將jdbc-driver部署到該項目中。現在沒問題。 – aime