【发布时间】:2013-10-25 05:29:20
【问题描述】:
我发现无法在标准区域(如 UTC)中将日期/时间插入 MySQL 数据库。
以下代码段使用 Apache DBCP 对用户进行身份验证。
public final class AuthenticationDAO {
public boolean isAuthenticated(String userName, String password) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
boolean status = false;
try {
connection = DatabaseConnection.getConnection();
preparedStatement = connection.prepareStatement("select * from admin_tbl where lower(admin_id)=lower(?) and BINARY password=?");
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
resultSet = preparedStatement.executeQuery();
status = resultSet.next();
if (status) {
preparedStatement = connection.prepareStatement("update admin_tbl set last_login=? where lower(admin_id)=lower(?) and BINARY password=?");
preparedStatement.setTimestamp(1, new Timestamp(new Date().getTime())); // java.util.Date / java.sql.Timestamp
preparedStatement.setString(2, userName);
preparedStatement.setString(3, password);
preparedStatement.executeUpdate();
}
} finally {
if (connection != null) {connection.close();}
if (resultSet != null) {resultSet.close();}
if (preparedStatement != null) {preparedStatement.close();}
}
return status;
}
}
此代码中只有一行是我们感兴趣的。
preparedStatement.setTimestamp(1, new Timestamp(new Date().getTime()));
当用户/管理员的登录尝试成功时,此行会更新登录日期/时间。 MySQL 中的列last_login 的类型为DATETIME。
我想在 MySQL 的 UTC 区域中插入日期/时间,但这不会发生。看来它需要一个本地区域。
无论如何,是否可以将日期/时间插入 UTC 区域的 MySQL 中?可以建议 Java 和/或 MySQL 中的任何数据类型 - 不仅是我在这里介绍的。
【问题讨论】:
标签: java mysql jdbc timezone utc