我使用intelliJ和MySQL在Java中构建了一个应用程序。我遇到类似以下的错误
“服务器时区值'×åéìåñéíÞGTB'无法识别或代表多个时区。您必须配置服务器或JDBC驱动程序(通过serverTimezone配置属性)以使用更特定的时区值想利用时区支持。“
我尝试使用jdbc:mysql:// localhost:3306 / schooldb?useLegacyDatetimeCode = false&serverTimezone = UTC代替jdbc:mysql:// localhost:3306 / schooldb,但问题仍然存在。
我使用mysql-connector-java-8.0.15
我的代码是
public class Database {
private MysqlDataSource dataSource;
private Connection con;
public Database(){
dataSource = new MysqlDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("schooldb");
try{
con = dataSource.getConnection("tei", "cangetin");
}catch(SQLException e){
e.printStackTrace();
}
}
protected void finalize() throws Throwable{
super.finalize();
con.close();
}
}
和
Database db = new Database();
[谁能帮我吗
您可以使用以下代码中的MysqlDataSource.setServerTimezone
。通过将系统区域设置(在Windows上)设置为不同于英语的某种语言(并重新启动MySQL),我用mysql-connector-java:8.0.18
重现了该异常,该编辑解决了连接问题。
public Database() throws SQLException {
dataSource = new MysqlDataSource();
dataSource.setServerName("localhost");
dataSource.setDatabaseName("schooldb");
dataSource.setServerTimezone("UTC");
try {
con = dataSource.getConnection("username","pass");
CallableStatement call = con.prepareCall("show databases;");
ResultSet res = call.executeQuery();
while(res.next()) {
System.out.println(res.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
奇怪的时区来自MySQL服务器配置。如果执行SQL:
SHOW VARIABLES LIKE '%zone%';
然后您会发现变量system_time_zone
的值很奇怪。最终,您可以改为在my.ini
文件中编辑设置:
[mysqld]
...
default-time-zone='+00:00'