我正在使用jsp文件和mysql。我在将日期和时间插入数据库时遇到问题。我可以插入其他信息,但只能插入日期和时间。我也需要将日期和时间插入数据库。我该如何实现?任何帮助表示赞赏。
Jsp代码
<%
String userId = request.getParameter("UserID");
String arm = request.getParameter("Arm");
String[] armNumber = request.getParameterValues("ArmNumber");
String remark = request.getParameter("Remark");
String Timestamp = request.getParameter("Time");
out.println("<tr>");
out.println("<td style='width: 10%'>");
out.println(Timestamp);
out.println("</td>");
out.println("</tr>");
int count =0;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String connURL = "jdbc:mysql://localhost/Dodo?user=Dodo&password=0000";
conn = DriverManager.getConnection(connURL);
if (armNumber != null){
for(int i=0; i<armNumber.length; i++){
String sql="Insert into assign(UserID, Arm, ArmNumber, Remark, Time) Values(?,?,?,?,now())";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString (1,userId);
pstmt.setString (2,arm);
pstmt.setString (3,(armNumber[i]));
pstmt.setString (4,remark);
int rec=pstmt.executeUpdate();
if (rec==1)
count++;
}
}
%>
<form action="assign.jsp" method="post">
<label><%=count%> assigned!!</label>
<td style width="50%">
<p><input type="submit" value="Return" name="ReturnBtn" /></p>
</form>
<%
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
}
%>
答案 0 :(得分:0)
First write sql
statement like
String sql="Insert into assign(UserID, Arm, ArmNumber, Remark, Time) Values(?,?,?,?,?)";
Then add some extra statement under pstmt.setString (4,remark);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
pstmt.setDate(5,dateFormat.format(date));
答案 1 :(得分:0)
now()
包含在sql
中的String
中,我假设您正在寻找一种名为now()
的方法,该方法返回当前时间和日期,但是因为String
内没有调用该方法。您需要执行以下操作:
String sql="Insert into assign(UserID, Arm, ArmNumber, Remark, Time) Values(?,?,?,?,?)";
....
pstmt.setString(1,userId);
pstmt.setString(2,arm);
pstmt.setString(3,(armNumber[i]));
pstmt.setString(4,remark);
pstmt.setTimestamp(5, new Date());//this is java.util.Date