2017-03-17 91 views
1

我已經嘗試從輸入到mysql數據庫存儲日期,但值仍然爲空。無論如何要使它工作?另外它說'數據添加',但它沒有插入到數據庫中,並在控制檯下面,它給NullPointerException。如何將日期從datepicker存儲到MySQL數據庫?

JSP頁面

<html> 
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" /> 
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
    <script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<title>Date Input</title> 
<script> 
    $(function(){ 
     $('.datepicker').datepicker(); 
    }); 
</script> 
</head> 
<body> 
    <form action="Date" method="post"> 
     <div class="row"> 
     Date: <input class="datepicker" type="text" name="date" id="date"> 
     </div> 
     <input type="submit" value="save"> 
    </form> 
</body> 
</html> 

連接Java類

package com.jsppractise; 
public class Date extends HttpServlet { 

    private static final long serialVersionUID = 1L; 

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     try { 
      response.setContentType("text/html"); 
      PrintWriter out = response.getWriter(); 
      String dt = request.getParameter("date").toString(); 

      Class.forName("com.mysql.jdbc.Driver"); 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sportsevent", "root", "root"); 

      PreparedStatement ps = con.prepareStatement("insert into date (date) values(?)"); 
      java.util.Date date = new SimpleDateFormat("MM/dd/yyyy").parse(dt); 
      java.sql.Date d = new java.sql.Date(date.getTime()); 
      ps.setDate(1, d); 
      ps = con.prepareStatement("select * from date"); 
      ResultSet s; 
      s = ps.executeQuery(); 
      if (s != null) { 
       System.out.println("date added"); 
      } else { 
       System.out.println("not added"); 
      } 

      out.print("<html><body><table><th>Date</th>"); 
      out.print("<tr><td>" + s.getDate(1) + "</td></tr>"); 
      out.print("</table></body></html>"); 
     } catch (Exception e) { 
      System.out.println(e); 
     } 
    } 
} 

回答

2

你永遠在執行插入語句,添加一個executeUpdate電話:

PreparedStatement ps = con.prepareStatement("insert into date (date) values(?)"); 
    java.util.Date date = new SimpleDateFormat("MM/dd/yyyy").parse(dt); 
    java.sql.Date d = new java.sql.Date(date.getTime()); 
    ps.setDate(1, d); 
    ps.executeUpdate();// ADDED 

    ps = con.prepareStatement("select * from date"); 
    ResultSet s = ps.executeQuery(); 

一第二引述@SpringLearner:

記得關閉連接,ResultSet和PreparedStatement

+1

記得關閉連接,ResultSet和PreparedStatement – SpringLearner

相關問題