JDBC 准备好的语句.setDate(....) 不节省时间,只是日期.. 我怎样才能节省时间? [英] JDBC Prepared Statement . setDate(....) doesn't save the time, just the date.. How can I save the time as well?

查看:22
本文介绍了JDBC 准备好的语句.setDate(....) 不节省时间,只是日期.. 我怎样才能节省时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下查询:

INSERT INTO users (user_id, date_created) VALUES (?,?)

我有以下准备好的声明

PreparedStatement insertUser = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

insertUser.setInt(1, 7);
java.util.Date now = new java.util.Date(System.currentTimeMillis());
insertUser.setDate(2, new java.sql.Date((new Date(System.currentTimeMillis())).getTime()));
insertUser.executeUpdate();

如果我检查数据库,我发现它只插入了今天的日期而不是时间,所以它会是:2011-07-29 00:00:00

If I check the database, I find that it is inserting only today's date not the time though, so it would be : 2011-07-29 00:00:00

我应该在 setDate() 中放什么来获取时间?

What should I put in the setDate() to get the time as well?

推荐答案

你应该使用 TimestampsetTimestamp 方法.

Instead of Date you should use a Timestamp and the setTimestamp method.

实际上你必须做这样的事情:

pratically you have to do something like that:

private static java.sql.Timestamp getCurrentTimeStamp() {
    java.util.Date today = new java.util.Date();
    return new java.sql.Timestamp(today.getTime());
}

....

preparedStatement.setTimestamp(4,getCurrentTimeStamp());

这篇关于JDBC 准备好的语句.setDate(....) 不节省时间,只是日期.. 我怎样才能节省时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆