1. Summary of date and time types in Java and MySQL:
| 1234567891011121314151617 |
mysql(版本:5.1.50)的时间日期类型如下:datetime 8bytes xxxx-xx-xx xx:xx:xx 1000-01-0100:00:00到9999-12-3123:59:59timestamp 4bytes xxxx-xx-xx xx:xx:xx 1970-01-0100:00:01到2038date 3bytes xxxx-xx-xx 1000-01-01到9999-12-31year 1bytes xxxx 1901到2155time 3bytes xx:xx:xx -838:59:59到838:59:59(为了满足时间的加减运算) ------------------------------------------------------------------------java(1.6) 中能保存时间日期类型的类主要有java.util.Datejava.util.Calendarjava.sql.Datejava.sql.Timejava.sql.Timestamp |
2. Java provides three types of data that are easy to interact with MySQL
Java.sql.Date
Java.sql.Time
Java.sql.Timestamp
They are inherited java.util.Date, which is a simplification of the class, and it is good for interacting with the database.
For Java.util.Date, the time and date types that were previously queried from MySQL are placed in the Java.util.Date type. This brings a series of problems, first of all, this class provides the time operation function is too few, generally need to convert to Java.util.Calendar again to operate.
For Java.util.calendar,calendar with powerful jump and interval operations, you can turn the time of the SQL series into Calendar when needed.
Set Calendar to Calendar, then convert from SQL Series time, and then back to SQL series time.
3. Experiment: Java >> MySQL
| 12345678910111213141516171819 |
===========java注入数据库==========java类型 mysql类型 成功与否date date yesdate time nodate timestamp nodate datetime notime date notime time yestime timestamp notime datetime no timestamp date yestimestamp time yestimestamp timestamp yestimestamp datetime yes==========end java注入数据库========总规律,如果A完全包含B,则A可以向B注入数据,否则报错 |
4. Experiment: MySQL >> java
| 1234567891011121314151617181920 |
==========从数据库提取到java ==========mysql类型 java类型 成与否date date yesdate time yes --------------缺少的部分使用历元date timestamp yes --------------缺少的部分使用历元 time date yes --------------缺少的部分使用历元time time yestime timestamp yes --------------缺少的部分使用历元timestamp date yestimestamp time yestimestamp timestamp yesdatetime date yesdatetime time yesdatetime timestamp yes==========end 从数据库提取到java=======不会出错,缺少的部分使用历元,而不是当前日期时间 |
5. When the date value in the database is null, read it when the Java object is instantiated:
| 12345 |
nullto db(null) =====> 也是nullnullto db(not null)=======> 数据库报错db(null) to java==========> 如果单字段出来,则整个entity都是null,如果带着其他不是null的字段出来,则可以实例化entity,本身字段依然是nulldb(not null) to java==========> 如果包含日期,则报错,否则为000最优解决方案,定义成可以为null |
Consolidation of date types in Java and date types in MySQL