如何将日期从datepicker存储到mysql数据库?

时间:2017-03-17 10:09:14

标签: java mysql jdbc

我已尝试将日期从输入存储到mysql数据库,但该值仍为null。反正有没有让它工作?它还说'数据已添加',但它没有插入数据库中,而是在控制台下面,它会产生NullPointerException。

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);
        }
    }
}

1 个答案:

答案 0 :(得分: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:

  

请记住关闭连接,结果集和预备声明