思考:在往数据库写数据时,如果写的是日期,并且代码中使用的是UtilDate,那么会有什么问题呢?
测试代码
package com.example.calender;
import com.example.calender.dto.DateDto;
import com.example.calender.mapper.TestMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.Date;
@SpringBootTest
public class Test {
@Autowired
private TestMapper testMapper;
@org.junit.jupiter.api.Test
public void test(){
DateDto dto = new DateDto();
//插入日期Date
Date date = new Date();
System.err.println(date);
dto.setDate(date);
//插入日期String
String str = "20220703";
System.err.println(str);
dto.setTime(str);
testMapper.insert(dto);
}
}
我们知道UtilDate打印出来的格式是下面这样的
Sun Jul 03 02:46:43 CST 2022
如果写入数据库表的日期格式为这样的
那么插入的数据就是这样的
看着好像没问题,也就是说即使插入的是UtilDate,到了数据库也会帮我们自动转成SQLDate
同理,如果我们将数据库的字段格式改成datetime
那么重新插入的数据就会变成datetime格式,但之前插入的数据则还是date格式
serverTimezone=Asia/ShanghaiSpringBoot整合MyBatis连接数据库配置
spring:
datasource:
username: root
password: root
url: jdbc:mysql://121.5.160.142:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml
那么插入日期字符串可以吗?
测试代码,如上
//插入日期String
String str = "20220703";
System.err.println(str);
dto.setTime(str);
同样我们给数据库加一个字段ti,格式为date
此时发现即使我们传给数据库的日期格式为20220703的字符串,数据库也可以帮我们解析出正确的SQLDate格式保存起来,数据库默默无闻地帮我们做了很多事
同时我们也可以传类似于2022-07-03或者2022-07-03 00:00:12这种的日期字符串,数据库一样可以解析成字段的格式保存起来
但是形如20220703 00:00:01这样的字符串日期格式,数据库也无能为力了,因为他根本不是数据认识的日期格式,此时数据库也会提醒我们更改格式
Incorrect date value: '20220703 00:00:01' for column 'ti' at row 1总结
如果是日期类型,那么我们可以很放心的存入到数据库的date或者datetime字段中,因为数据库会帮我们将数据转成他想要的样子
但如果是字符串类型,我们就得注意了,常见的数据库也可以识别并帮我们存起来,比如20220202;2022-02-02;2022-02-02 00:00:12等,但是不常见的日期字符串类型,数据库也可能不认识,此时就需要我们对数据作进一步处理了,然后将符合的日期格式传给数据库
此外,在连接数据库时也要注意时区问题,不然可能会导致数据的时间和数据库保存的时间不一致,此类问题,请询问万能的百度吧~



