在Java MySQL数据库调用中无法识别日期类型

在Java MySQL数据库调用中无法识别日期类型,java,mysql,jdbc,Java,Mysql,Jdbc,我的一个类中有以下调用 @Override public Integer save(NewsItem item){ ConnectionPool pool = new ConnectionPool(); Connection connection = pool.getConnection(); PreparedStatement ps = null; try{ String query = "INSERT INTO newsItem (type,t

我的一个类中有以下调用

@Override
public Integer save(NewsItem item){
    ConnectionPool pool = new ConnectionPool();
    Connection connection = pool.getConnection();
    PreparedStatement ps = null;
    try{
        String query = "INSERT INTO newsItem (type,title,content,link,layout,imageUri,timestamp)" +
                       "VALUES (?,?,?,?,?,?,?)";
        ps = connection.prepareStatement(query);
        ps.setInt(1,item.getType());
        ps.setString(2,item.getTitle());
        ps.setString(3,item.getContent());
        ps.setString(4,item.getLink());
        ps.setInt(5,item.getLayout());
        ps.setString(6,item.getImageUri());
        ps.setDate(7,item.getTimestamp());

        return ps.executeUpdate();
    }
    catch(SQLException e){
        e.printStackTrace();
        return 0;
    }
    finally{
        ConnectionUtility utility = new ConnectionUtility();
        utility.closePreparedStatement(ps);
        pool.freeConnection(connection);
    }
}
NewsItem POJO具有以下属性

private Integer id; private Integer type; private String title; private String content; private String link; private Integer layout; private String imageUri; private Date timestamp; 私有整数id; 私有整数类型; 私有字符串标题; 私有字符串内容; 私有字符串链接; 私有整数布局; 私有字符串imageUri; 私有日期时间戳; 除了时间戳调用之外,所有的东西都可以工作并且已经过测试

ps.setDate(7,item.getTimeStamp()) ps.setDate(7,item.getTimeStamp()) 我可以通过调用

item.setTimestamp(new Date()); item.setTimestamp(新日期()); 但是我从IDE(Eclipse)中得到错误,它告诉我以下消息

NewsItemDAO类型中的方法setDate(int,Date)不适用于参数 设置日期(整数,日期)

在我一直在开发的这个应用程序的整个生命周期中,这一直是困扰我的一个问题,因为我不得不暂时将时间戳存储为字符串


如果MySQL数据库中的列是DATETIME类型,是否有其他方法可以保存该时间戳?还是调用有问题?

检查您的导入-我猜您使用的是
java.util.Date
而不是
java.sql.Date

如果可能的话,最好使用
java.sql.Timestamp
,它扩展了
java.util.Date
,以避免这种混淆并增强代码的可读性。

预期的,而不是预期的

但是
java.sql.Date
只包含datetime的日期部分,而不包含时间部分。你想改用


在这种情况下,问题不在于进口。然而,
Timestamp
建议是附议的,但这不仅仅是因为可读性。这种方法是否适用于MySQL,我是否仍然可以像使用java.util.Date那样使用java.sql.Timestamp?这个MySQL数据类型应该是TIMESTAMP还是DATETIME?您不应该在模型对象(您称之为POJO)中使用
java.sql.TIMESTAMP
。仅在数据库中持久化期间使用它。在检索时,您可以将
ResultSet#getTimestamp()
向上转换为
java.util.Date
。至于类型,您可以同时使用这两种类型。不同之处在于,
时间戳
隐式转换为UTC时区,因此更建议避免时区问题和不可移植性。非常好!我做了改变。只要我能在POJO上来回输入日期类型,并在从数据库中取出时输入值,一切看起来都很好。
ps.setDate(7, new java.sql.Date(item.getTimestamp().getTime()));
ps.setTimestamp(7, new Timestamp(item.getTimestamp().getTime()));