简体   繁体   中英

Inserting dates into MySQL

When doing JUnit tests I have to insert values into the database. For doing this I have a file (import.sql) which contains various inserts for various tests. It works perfect expect for dates. How would I have to format dates so that MySQL would be able to import them as dates.

The java entity

import java.util.Date;

@Entity
@Table(name = "TEST")
public class Test {

    @Column(name = "START")
    @Temporal(TemporalType.DATE)
    private Date startDate;

    @Column(name = "END"
    @Temporal(TemporalType.DATE)
    private Date endDate;

    // getter & setter
}    

Snippet from the import.sql

INSERT INTO TEST (START, END) VALUES ('2015-07-20 22:00:00.000', '2015-07-20 23:30:00.000')
INSERT INTO TEST (START, END) VALUES ('2015-08-18 21:00:00.000', '2015-08-18 22:30:00.000')

In this case 2015-08-18 21:00:00.000 , but this doesn't work. It results in an error telling that the format isn't correct.

Loading from import.sql

<property name="javax.persistence.sql-load-script-source"
        value="import.sql" />

How has the date be formatted?

要匹配输入值2015-08-18 21:00:00.000START字段和END字段类型应为DATETIME(3)

Just use '2015-07-20 22:00:00', so stript the fraction of the seconds from the end if you are not using them any way. Fractional second support has been added in v5.6.4, so you may have compatibility issues if you have earlier versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM