数据库表结构: sacno varchar(30), name varchar(45), fname varchar(45), dob date;
这是jsp页面 -
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script language="javascript" type="text/javascript" src="caljs/MyCalender.js"></script>
<script language="javascript" type="text/javascript" src="caljs/validateDate.js"></script>
<link href="caljs/MyCalender.css" rel="stylesheet" type="text/css">
</head>
<body>
<form action="AddNewMember.jsp" method="post">
<h1>New Member Account </h1>
<table align="center">
<tbody align="left">
<tr>
<td class="td-color">Name*</td>
<td class="td-border"><input type="text" name="mname" placeholder="Enter Name"/></td>
<td class="td-color">Father Name:*</td>
<td class="td-border"><input type="text" name="fname" placeholder="Enter Father's Name"/></td>
</tr>
<tr>
<td class="td-color">Date of Birth:*</td>
<td class="td-border"><input type="text" name="dob" placeholder="Date of Birth" id="inputField" onfocus="displayCalendar('inputField','dd/mm/yyyy',this)"/></td>
<td class="td-color">Society Account Number:*</td>
<td class="td-border"><input type="text" name="sacno" placeholder="Society Account Number"/></td>
</tr>
<tr>
<td> <input type="submit" value="Submit"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
String name=request.getParameter("mname");
String fname=request.getParameter("fname");
String dob=request.getParameter("dob");
String sacc=request.getParameter("sacno");
DateFormat df=new SimpleDateFormat("dd/MM/yyyy");
Date dob1=null;
java.sql.Date sd=null;
dob1=(Date)df.parse(dob);
sd=new java.sql.Date(dob1.getTime());
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
PreparedStatement ps=con.prepareStatement("insert into member values(?,?,?,?)");
ps.setString(1,sacc);
ps.setString(2,name);
ps.setString(3,fname);
ps.setDate(4,sd);
int i=ps.executeUpdate();
if(i>0)
{
response.sendRedirect("Member.jsp");
}
}
catch(Exception e)
{
out.print(e);
}
运行时会出现以下异常: java.lang.ClassCastException:java.util.Date无法强制转换为java.sql.Date。 请帮帮我。
答案 0 :(得分:0)
将日期转换为java.sql.Date 像
这样的东西java.sql.Date sqlDate =new java.sql.Date(new java.util.Date().getTime());
它应该有用。
java.util.Date utilDate = new java.util.Date();
System.out.println("java.util.Date : " + utilDate);
java.sql.Date sqlDate = dateConvert(utilDate);
System.out.println("java.sql.Date: " + sqlDate);
DateFormat df = new SimpleDateFormat("dd/MM/YYYY - hh:mm:ss");
System.out.println("Apply Date format : " + df.format(utilDate));
}
private static java.sql.Date dateConvert(java.util.Date utilDate) {
java.sql.Date d = new java.sql.Date(utilDate.getTime());
return d;
}