-首先给出代码以及所报异常
package day01;
/*
jdbc入门
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class jdbcDemo1 {
public static void main(String[] args) throws Exception {
//导入jar包
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接对象
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
//定义sql语句
String sql = "update account set balance = 500 where id = 1";
//获取执行sql对象
Statement stmt = connection.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println(count);
stmt.close();
connection.close();
}
}
报错如下:
一段一段看。。。
控制台首先输出:
Loading class “com.mysql.jdbc.Driver”. This is deprecated. The new
driver class is “com.mysql.cj.jdbc.Driver”. The driver is
automatically registered via the SPI and manual loading of the driver
class is generally unnecessary.
翻译下来就是:
加载类“ com.mysql.jdbc.Driver”。 不推荐使用。 新的驱动程序类是“
com.mysql.cj.jdbc.Driver”。 通过SPI自动注册驱动程序,通常不需要手动加载驱动程序类
这个问题我所寻找的答案就是:
- 当使用驱动mysql-connector-java 5时,JDBC连接MySQL应使用com.mysql.jdbc.Driver
- 当使用驱动mysql-connector-java6及以上版本时,JDBC连接MySQL应使用com.mysql.cj.jdbc.Driver ,同时,还需要指定时区serverTimezone(这也是下面报错的原因)
所以这里需要修改代码:
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
------------------->
Class.forName("com.mysql.cj.jdbc.Driver");
接下来是下面的报错输出:
The server time zone value ‘�й���ʱ��’ is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the ‘serverTimezone’ configuration property) to use a more specifc time zone value if you want to utilize time zone support.
翻译下来就是:
无法获取JDBC连接; 嵌套的异常为java.sql.SQLException:服务器时区值“”。无法识别或表示多个时区。
如果要利用时区支持,则必须配置服务器或JDBC驱动程序(通过“ serverTimezone”配置属性)以使用更特定的时区值。
这个问题主要是我们没有设置时区,在设定时区的时候,如果设定serverTimezone=UTC,会比中国时间早8个小时,如果在中国,可以选择Asia/Shanghai或者Asia/Hongkong。
这里所需要修改的代码:
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
---------------------------
DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai", "root", "123456");
到这里再重新运行就没问题了