使用java将日期时间插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2980078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:11:46  来源:igfitidea点击:

inserting datetimes into database using java

javamysqldatetimeprepared-statement

提问by

I am wanting to insert a datetime into a MySql data base using Java and a prepared statement:

我想使用 Java 和准备好的语句将日期时间插入到 MySql 数据库中:

Calendar cal = Calendar.getInstance();
PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " +
                       "(Time) VALUE (?) ");
    stmnt.setDate(1, new java.sql.Date(cal.getTime()));
    stmnt.executeQuery();  

NOTE: there is currently an error - cannot find symbol (java.sql.Date) line 4 here

注意:当前存在错误 - 无法在此处找到符号 (java.sql.Date) 第 4 行

db is an instance of a sort of wrapper class that exposes what I need from java.sql - its just getting a prepared statement from my connection object here.

db 是一种包装类的实例,它从 java.sql 公开我需要的内容 - 它只是从我的连接对象中获取准备好的语句。

Time (the column) is a date time in my database, and I can only see setDate and setTime method but I want to store both - also my code does not work anyway ;-)

时间(列)是我数据库中的日期时间,我只能看到 setDate 和 setTime 方法,但我想同时存储两者 - 而且我的代码无论如何都不起作用;-)

If anyone could give me some pointers on inserting a combined date time (current time would be a great help as that's my first goal) into a MySql DB using a prepared statement I would be very grateful.

如果有人可以给我一些关于使用准备好的语句将组合日期时间(当前时间将是一个很大的帮助,因为这是我的第一个目标)插入到 MySql DB 中的指示,我将非常感激。

Thanks

谢谢

采纳答案by Goibniu

The constructor for java.sql.Date takes a long (milliseconds since 1970) java.sql.DateTo get milliseconds from a java.uitl.Calendar, you use cal.getTimeInMillis()

java.sql.Date 的构造函数需要很长时间(自 1970 年以来的毫秒数)java.sql.Date要从 java.uitl.Calendar 获取毫秒,您可以使用cal.getTimeInMillis()

Your code would be:

您的代码将是:

Calendar cal = Calendar.getInstance();
PreparedStatement stmnt = db.PreparedStatement("INSERT INTO Run " + "(Time) VALUE (?) ");
stmnt.setDate(1, new java.sql.Date(cal.getTimeInMillis()));
stmnt.executeQuery();

回答by Chris

the following code should allow you to insert a date with millisecond accuracy. I have used it with HSQLDB, Sybase, SQL-Server and MySql without any problems.

以下代码应该允许您以毫秒精度插入日期。我已经将它与 HSQLDB、Sybase、SQL-Server 和 MySql 一起使用,没有任何问题。

java.util.Date date = getMyDate();
if (date == null) {
    statement.setNull(insertionIndex, Types.TIMESTAMP);
} else {
    statement.setTimestamp(insertionIndex, new Timestamp (date.getTime()));
}