eclipse连接mysql(8.0)的版本问题

项目通过采用JDBC连接mysql数据库。

  • 导入jar包

首先需要在项目中导入两个jar包,分别是Access_JDBC40.jar和mysql-connector-java-xxxx.jar。其中后者版本需要与mysql的版本相匹配,需要导入8.0及以上的版本,这里采用的是mysql-connector-java-8.0.15.jar,各个版本的mysql-connector-java的jar包在https://mvnrepository.com/artifact/mysql/mysql-connector-java

如果导入的jar包版本不符或者未导入相应的jar包,则会报出如下错误:

在eclipse中导入jar包的方法如下:

在项目上点击右键,按顺序点击Build Path>>Add External Archives,进入相应的文件夹中选择需要导入的jar包,最后点击打开按钮即可。导入效果如下图:

 在eclipse中移除jar包的方法如下:

 在项目上点击右键,按顺序点击Build Path>>Configure Build Path,选择需要移除的jar包点击remove即可。

 

  •  通过相关代码对数据库进行访问

Java连接mysql数据库的过程一般如下:

首先声明Connection变量con并初始化,定义相关的变量(驱动名称driver,url,用户名user以及密码password)。

之后,通过Class.forName()方法加载驱动,参数为driver。

接着,通过DriverManager.getConnection()方法 对数据库进行访问,参数为:url,user,password。

最终判断条件(!con.isClosed()),如果成立,则说明成功访问数据库,再进行下一步操作。

需要注意的是,在与之前的版本相比,变量的赋值上有几处变化:

之前的版本:

String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/tree?useUnicode=true&characterEncoding=utf-8";
String user="root";
String password="xxxxxxxxx";

针对mysql8.0的版本,需要更改driver和url,否则会出现错误:

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.
            java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near ';characterEncoding=utf-8'.

结果如图所示:

更改之后如下:

String driver="com.mysql.cj.jdbc.Driver";//驱动名称
String url="jdbc:mysql://localhost:3306/wens?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT"
String user="root";            //用户名
String password="xxxxxxxx";    //密码

最终可以实现对mysql数据库的访问。

猜你喜欢

转载自blog.csdn.net/MonsterZw/article/details/87641148