JDBC实现mysql数据库的连接

在首次使用数据库连接时,常出现的两个问题就是:

一:数据库驱动链接出现问题,也就是驱动不匹配

最新版本的数据库驱动需要输入:com.mysql.cj.jbdc.Driver  

注意上面的“cj”很重要,

二:就是设置时区问题,因为默认的时区是美国的时区0,而我们国家的时区是8 所以需要我们自己手动设置

在cmd下设置mysql的时区:

输入: show variables like '%time_zone%';

如果显示time_zone    |     SYSTEM
则需要我们修改时区了
 再次输入: set time_zone='+8:00';
即可转换到我们的东八时区
要看是否设置成功,可以重新输入 show variables like '%time_zone%';查看,或者出现OK,0 rows effected,即说明设置成功
这时可以重新启动eclipse开发工具,即可连接数据库成功

连接数据库时显示:

java.sql.SQLException: 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.

try {
// 最新驱动需要加com.mysql.cj.jdbc.Driver
// com.mysql.cj.jdbc.Driver //目前我使用的是最新的mysql驱动版本
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//
try {

// 下面这段话用于设置mysql的时区问题
// jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
con=DriverManager.getConnection("jdbc:mysql:"+ "//127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false","root","root");
// con=DriverManager.getConnection("jdbc:mysql:"+ "localhost","root","root");
System.out.println("数据库链接成功!");
}catch(SQLException e) {
e.printStackTrace();

猜你喜欢

转载自www.cnblogs.com/Jack1816274408/p/10644723.html