背景:
最近接触到一个新项目,在插入数据时发现插入的时候不正确。于是有了以下探究历程。
项目后台使用的是jdbcTemplate:
对应插入时间字段mysql类型:datetime
插入时使用java 中 new Date(),之后交由jdbcTemplate 进行数据插入操作。
问题:
首先通过debug 确认 newDate() 生成时间正确为本地时间。开始怀疑是不是jdbcTemplate里面出了什么幺蛾子。
// jdbctemplate 执行插入语句入口
public int[] batchUpdate(String sql, List<Object[]> batchArgs) throws DataAccessException
{
return this.batchUpdate(sql, batchArgs, new int[0]);
}
// 一路跟踪我们可以发现它会先进行参数的赋值
StateMentCreatorUtils.class(142-243)
//sqlType = -2147483648
else if (sqlType == -2147483648 || sqlType == 1111 && "Oracle".equals(ps.getConnection().getMetaData().getDatabaseProductName())) {
// 如果是字符串的话 不需要进行任何转变 直接赋值
if (isStringValue(inValue.getClass())) {
ps.setString(paramIndex, inValue.toString());
}// 如果是日期类型需要进行 日期转换
else if (isDateValue(inValue.getClass())) {
ps.setTimestamp(paramIndex, new Timestamp(((Date)inValue).getTime()));
} else if (inValue instanceof Calendar) {
cal = (Calendar)inValue;
ps.setTimestamp(paramIndex, new Timestamp(cal.getTime().getTime()), cal);
} else {
ps.setObject(paramIndex, inValue);
}
通过上述跟踪可以发现 应该是setTimestamp时出现了问题。这个方法是在mysql驱动包里面的。继续跟进
x = TimeUtil.adjustTimestampNanosPrecision(x, fractionalLength, !this.session.getServerSession().isServerTruncatesFracSecs());
// 获取当前连接的时区,进行format
this.tsdf = TimeUtil.getSimpleDateFormat(this.tsdf, "''yyyy-MM-dd HH:mm:ss", targetCalendar,
targetCalendar != null ? null : this.session.getServerSession().getDefaultTimeZone());
StringBuffer buf = new StringBuffer();
buf.append(this.tsdf.format(x));
跟到这里的时候。这个 this.session.getServerSession().getDefaultTimeZone()); 不就是获取时区嘛,我本地没有指定,因此应该是默认时区,因此插入时间有问题。所以开始在连接串上加上 指定时区 Asia/Shanghai。测试通过。
BUT
我记得之前写过的小程序也好,项目也好,很少会在连接串上加上时区。看了一眼版本,8.0.19 。emmm 原来一直用的5.x。难道这中间又有啥问题,本着杠精的精神又开始了一趟奇妙旅行。
设计以下程序:
public class Main {
// // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
// static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// static final String DB_URL = "jdbc:mysql://localhost:3306/test";
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
// 系统时区
Timestamp timestamp = new Timestamp(new Date().getTime());
sql = "insert into test (create_time,mysql_driver) values (?,?) ";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setTimestamp(1,timestamp);
if(("com.mysql.jdbc.Driver").equals(JDBC_DRIVER)){
ps.setNString(2,"mysql-connector-5");
}else{
ps.setNString(2,"mysql-connector-8");
}
ps.executeUpdate();
// 更改时区
System.setProperty("user.timezone", "GMT-6");
TimeZone.setDefault(TimeZone.getTimeZone("GMT-6"));
timestamp = new Timestamp(new Date().getTime());
sql = "insert into test (create_time,mysql_driver) values (?,?) ";
ps=conn.prepareStatement(sql);
ps.setTimestamp(1,timestamp);
if(("com.mysql.jdbc.Driver").equals(JDBC_DRIVER)){
ps.setNString(2,"mysql-connector-5");
}else{
ps.setNString(2,"mysql-connector-8");
}
ps.executeUpdate();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
首先运行 5 可以看到插入结果(emm,和预想的差不多)
接着运行8 查看结果(0.0)
这就8太秒了,为什么插入的时间是相同的。
于是开始探究 5的时间设置源码:
// 获取时区
synchronized(sessionCalendar) {
x = TimeUtil.changeTimezone(this.connection, sessionCalendar, targetCalendar, x, tz, this.connection.getServerTimezoneTZ(), rollForward);
}
if (this.connection.getUseSSPSCompatibleTimezoneShift()) {
this.doSSPSCompatibleTimezoneShift(parameterIndex, x, sessionCalendar);
} else {
if (this.tsdf == null) {
this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss''", Locale.US);
}
timestampString = this.tsdf.format(x);
this.setInternal(parameterIndex, timestampString);
}
this.connection.getServerTimezoneTZ() 与8 中有明显区别。
一个是获取系统设置的时区,一个是获取session中的时区。session中的时区不会因为设置时区而改变,这样自然插入时间一致。至于为什么要这么设计,百度了一篇文章,有兴趣的可以看下: