如何使用JSP将当前时间和将来时间插入MySQL数据库

时间:2018-08-03 16:48:38

标签: java mysql jsp tomcat7

我很难在MySQL数据库中插入正确的日期时间。数据库设置为:

aucID,int(11)AI

最小价格,浮动

浮动起始价格

开始日期时间,日期时间

enddatetime,datetime

<%@ page import ="java.sql.*" %>
<% 



   try{
        String itemid = request.getParameter("itemid");   
        String startprice = request.getParameter("startprice");
        String minprice = request.getParameter("minprice");
        String startdate = request.getParameter("current");
        String enddate = request.getParameter("length");

        System.out.println(itemid);

        System.out.println(startprice);
        System.out.println(minprice);
        System.out.println(startdate);
        System.out.println(enddate);
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://xxx","xxx", "xxx");
        Statement st = con.createStatement();

        st.executeUpdate("INSERT INTO auctions (minprice, startprice, startdatetime, enddatetime, itemid) VALUES ('" + minprice + "','" + startprice + "','" + itemid + "','" + ADD CURRENT DATE + "','" + ADD FUTURE DATE + "')");
        con.close();

        String URL = "addauction.jsp";
        response.sendRedirect(URL); 

    }
    catch (SQLException e){
        System.err.println("Got an exception!");
        System.err.println(e.getMessage());
    }


    %>

我正在建立一个基本的拍卖网站。我需要能够设置创建拍卖的时间并设置拍卖结束的未来日期。

如果您也能够告诉我如何比较时间,那将非常有帮助。

提前谢谢!

3 个答案:

答案 0 :(得分:3)

如果使用准备好的语句,则可以使用java.sql.Timestamp类型绑定时间戳参数。

String sql = "insert into tbl (col1, col2, col3) values (?, ?, ?)";
PreparedStatement stmt = dbConnection.prepareStatement(sql);
stmt.setTimestamp(3, Timestamp.valueOf(new LocalDateTime().now()));
stmt.executeUpdate();

MySQL还接受DATETIME值作为字符串,格式为YYYY-MM-DD HH:MM:SS。您可以使用DateTimeFormatter以这种格式生成时间字符串:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

// 2018-08-03 03:50:17
LocalDateTime.now().format(formatter);

// 2018-09-03 03:50:17
LocalDateTime.now().plusMonths(1).format(formatter);

现在您要做的就是为表单参数(LocalDateTimestartdate)创建正确的enddate,然后绑定Timestamp参数或连接一个格式化的DATETIME字符串。

答案 1 :(得分:0)

首先,您需要将String“ startdate”转换为日期对象。然后添加一个将来的日期,或根据需要调整日期。

//Convert string to date.  
String string = "January 2, 2010";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss");
Date date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010

//Plus future day.
DateTime dtOrg = new DateTime(date);
DateTime dtPlusOne = dtOrg.plusDays(1);

答案 2 :(得分:0)

对我有用的解决方案是将Table中的TimeStamp字段配置为具有默认的Now(),因此,每次在数据库中添加某些内容而不提供该字段时,它将自动为您填充