![](/img/trans.png)
[英]Insert time and date in MySQL database using jsp,bean class and servlet
[英]How to insert current time and future time into MySQL database using JSP
我很難在MySQL數據庫中插入正確的日期時間。 數據庫設置為:
aucID,int(11)AI
minprice,float
startprice,float
startdatetime,datetime
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());
}
%>
我正在建立一個基本的拍賣網站。 我需要能夠設置創建拍賣的時間並設置拍賣結束時的未來日期。
如果你能告訴我如何比較時間,那將是非常有幫助的。
先感謝您!
如果您正在使用預准備語句,則可以使用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);
現在,您所要做的就是為表單參數( startdate
和enddate
)創建正確的LocalDateTime
,然后綁定Timestamp
參數或連接格式化的DATETIME
字符串。
首先,您需要將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);
適用於我的解決方案是將Table中的TimeStamp字段配置為默認的Now(),因此每次在DB中添加內容並且不提供該字段時,它都會自動為您填充。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.