java.util.Date cannot be cast to java.sql.Date 将date类型的数据存入数据库

页面接受的date是java.util.date,放入数据库要用java.sql.date,实现两者之间的转化:

1.user.java

package model;
import java.util.Date;
public class User {
	public String username,password,address,email;
	Date birth;
	public User(){
	}
	public User(String username, String password, String address, String email, Date birth) {
		super();
		this.username = username;
		this.password = password;
		this.address = address;
		this.email = email;
		this.birth = birth;
	}
	//getter,setter方法。。略	
}

2.add.jsp:注册页面(我写的是struts2项目,但是将date放入数据库的例子是常见的)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>


<%@taglib prefix="s" uri="/struts-tags" %>



注册











3.AddAction.java

package com;
import com.opensymphony.xwork2.ActionSupport;
import java.util.*;
import dao.AddDao;
import model.User;
public class AddAction extends ActionSupport{
	private static String FORWARD=null;//页面导向
	private User user =new User();
 	//private User user; 
   	public User getUser() {
       return user;
   	}
   	public void setUser(User user) {
       this.user = user;
   	}
	public String execute() throws Exception{
		AddDao dao=new AddDao();
		User u=new User();
		u=dao.findName(this.user.getUsername());
		if(u.getUsername()==null){
			System.out.println("注册成功");
			// System.out.println(this.user.getUsername());
			// System.out.println(u.getUsername());
			// System.out.println(u.getBirth());
			dao.add(this.user);//在AddDao中
			FORWARD="success";
		}
		else{
			System.out.println("注册失败");
			FORWARD="input";
		}
		return FORWARD;
	}
}

4.AddDao.java

package dao;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import model.User;

public class AddDao {
	Connection con;
	String driver="com.mysql.jdbc.Driver";
	String url="jdbc:mysql://localhost:3306/struts2";
	public AddDao(){
		try{ 
			Class.forName(driver);
			this.con=DriverManager.getConnection(url,"root","root");
		}catch(Exception e){
			e.printStackTrace();
		}
	}
/*

public void add(User user){
	String sql="INSERT INTO user(username,password,address,email,birth) VALUES ( ?, ?, ?, ? ,?)";
	try {
		PreparedStatement cmd=this.con.prepareStatement(sql);
		cmd.setString(1, user.getUsername());
		cmd.setString(2, user.getPassword());
		cmd.setString(3, user.getAddress());
		cmd.setString(4, user.getEmail());
		cmd.setDate(5, new java.sql.Date(user.getBirth().getTime()));//重点
		cmd.executeUpdate();
	} catch (SQLException e) {
	// TODO Auto-generated catch block
		e.printStackTrace();
	}
...
}


你可能感兴趣的:(数据库mysql)