日期:2014-05-19  浏览次数:20774 次

用Jsp做个网站,其中有一项需要向数据库中插入日期时间(时间格式形如2012-04-30),在数据库中该字段数据类型为datetime,现如今用户提交表单老是错
数据库中表 leavemessage 相关字段如下:
userid varchar(50)
pubtitle varchar(50)
pubcontent text
pubdate datetime
===============
package entity
import java.util.Date;
public class LeaveMessage{
private String userid;
private String pubtitle;
private String pubcontent;
private Date pubdate=new Date();
以下由Eclipse自动生成set、get方法
.
.
.}
===============
package dao
import java.util.*;
import java.sql.*;
import entity.
public class LeaveMessageDao{
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
int i=0;
public Connection getConnection(){
...
return conn //这都正常不写了
}
public int addLeaveMessage(LeaveMessage lm){
String sql="insert into leavemessage (userid ,pubtitle ,pubcontent ,pubdate )values(?,?,?,?)";
conn=getConnection();
try{
ps=conn.PrepareStatement(sql);
ps.setString(1,lm.getString("userid"));
ps.setString(2,lm.getString("pubtitle"));
ps.setString(3,lm.getString("pubcontent"));
ps.setDate(4,lm.new Date());i=ps.executeQuery();
}catch(Exception e){
e.getMessage();
}
return i;

}

}
===============
user.jsp
<%@ page language="java" pageEncoding="gbk"%>
<html>
<head>
<title>用户留言</title>
</head>
<body>
<form method="post" action="douser.jsp">
<tr>
<td>userid</td>
<td><input type="text" name="userid" /></td>
</tr>
<td>pubtitle</td>
<td><input type="text" name="pubtitle" /></td>
</tr>
</tr>
<td>pubcontent</td>
<td><input type="textarea" name="pubcontent" /></td>
</tr>
</tr>
<td><input type="submit" value="提交" /></td>
<td><input type="reset" value="重置" /></td>
</tr>
</form>
</body>
</html>
==============
douser.jsp
<%@ page import="entity.LeaveMessage,dao.LeaveMessageDao"%>
<%
request.setCharacterEncoding("gbk");
String s_userid=request.getParameter("userid");
String s_pubtitle=request.getParameter("pubtitle");
String s_pubcontent=request.getParameter("pubcontent");
LeaveMessage lm=new LeaveMessage();
LeaveMessageDao lmdao=new LeaveMessageDao();
lm.setUserid(s_userid);
lm.setPubtitle(s_pubtitle);
lm.setPubcontent(s_pubcontent);
int i=lmdao.addLeaveMessage();
if(i>0){
response.sendRedirect(index.jsp);
}else{
response.sendRedirect(user.jsp);

}
%>

------解决方案--------------------
ps.setDate(int,Date),这里的Date是java.sql.Date类型的,不能插入一个java.util.Date类型的Date对象,
可以这样转换一下:ps.setDate(i,new java.sql.Date(new java.util.Date().getTime()))