JAVA 使用JDBC连接mysql数据库的坑!!

JAVA 使用JDBC连接mysql数据库的坑!!

1.源代码展示

package com.xuanji.lesson01;

import java.sql.*;

//我的第一个jdbc程序
public class JDBCFirstDemo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.jdbc.Driver");//固定写法,加载驱动
        //2.用户信息和url
        String url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=true";
        String username="root";
        String password="******";//密码不便展示
        //3.连接成功,返回数据库对象
        Connection connection= DriverManager.getConnection(url,username,password);
        //4.执行SQL的对象
        Statement statement = connection.createStatement();
        //5.执行SQL的对象去执行SQL,可能存在结果,查看返回结果
        String sql="SELECT * FROM sp_type";
        ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,结果集中封装了我们全部的查询出来的结果
        while(resultSet.next()){
            System.out.println("type_id="+resultSet.getObject("type_id"));
            System.out.println("type_name="+resultSet.getObject("type_name"));
            System.out.println("delete_time="+resultSet.getObject("delete_time"));
        }
        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}

这个是源代码,乍一看是没有任何问题的。。。。

当你点击运行的时候,恐怖的事情就开始了,一堆报错。。。。

2.运行报错!!!

3.分析报错修改代码

我们先来看看报错的信息

3.1首先:

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这个目录下的,那我们首先找到这个错误,先把com.mysql.jdbc.Driver改为com.mysql.cj.jdbc.Driver

(版本问题,如果你直接用com.mysql.jdbc.Driver没有问题的话,嗯,就证明你的版本没有问题。。。。。)

3.2第二段报错

Exception in thread "main" 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.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:63)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:73)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:76)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at com.xuanji.lesson01.JDBCFirstDemo.main(JDBCFirstDemo.java:15)
Caused by: com.mysql.cj.exceptions.InvalidConnectionAttributeException: 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.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:85)
    at com.mysql.cj.util.TimeUtil.getCanonicalTimezone(TimeUtil.java:132)
    at com.mysql.cj.protocol.a.NativeProtocol.configureTimezone(NativeProtocol.java:2118)
    at com.mysql.cj.protocol.a.NativeProtocol.initServerSession(NativeProtocol.java:2142)
    at com.mysql.cj.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:1310)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:967)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:826)
    ... 6 more

 第二段报错跟第三段报错基本上是一个意思,就一起讲啦~~

首先看报错我们get到一个点就是server time报错,???

仔细阅读下去,它告诉我们的意思是我们的数据库和系统时区上有差异所造成的。

那要怎么解决这个问题呢???很简单

在JDBC连接的URL后面加上serverTimezone = GMT即可解决问题,如果需要使用GMT + 8时区,需要写成GMT%2B8(2B即"+“的十六进制ASCII码,”%2B"即“+”),否则会被解析为空。

4.修改后的代码

那现在把这些错误地方先改过来,改完的代码如下:

package com.xuanji.lesson01;

import java.sql.*;

//我的第一个jdbc程序
public class JDBCFirstDemo {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //1.加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");//固定写法,加载驱动
        //2.用户信息和url
        String url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=GMT";
        String username="root";
        String password="******";//密码不便展示
        //3.连接成功,返回数据库对象
        Connection connection= DriverManager.getConnection(url,username,password);
        //4.执行SQL的对象
        Statement statement = connection.createStatement();
        //5.执行SQL的对象去执行SQL,可能存在结果,查看返回结果
        String sql="SELECT * FROM sp_type";
        ResultSet resultSet = statement.executeQuery(sql);//返回的结果集,结果集中封装了我们全部的查询出来的结果
        while(resultSet.next()){
            System.out.println("type_id="+resultSet.getObject("type_id"));
            System.out.println("type_name="+resultSet.getObject("type_name"));
            System.out.println("delete_time="+resultSet.getObject("delete_time"));
        }
        //6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}

现在再来运行!!

5.运行结果:

成功啦!!!!没有报错,出来的效果也是我们要的效果啦!!!!

 

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在使用Java语言中的Idea集成开发环境连接MySQL数据库时,需要使用Java Database Connectivity(JDBC)技术。以下是连接MySQL数据库的步骤: 1.下载并安装MySQL数据库驱动程序。可以从官方网站下载MySQL Connector/J,或者使用Maven或Gradle等构建工具来获取驱动程序。 2.在Idea项目的classpath中添加MySQL数据库驱动程序。 3.编写Java代码来连接MySQL数据库。示例代码如下: ```java import java.sql.*; public class MysqlJdbcTest { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "123456"; Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, username, password); System.out.println("成功连接数据库!"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } ``` 在以上代码中,需要修改url、username和password变量的值以匹配实际的MySQL数据库连接信息。其中,url变量指定了MySQL服务器的地址和端口以及要连接数据库名称。username和password变量则指定了连接数据库所需的用户名和密码。最后,使用Java中的JDBC技术连接MySQL数据库,并在控制台输出连接成功信息。 ### 回答2: idea使用jdbc连接mysql数据库非常简单,只需要按照以下步骤进行操作即可。 步骤一:在pom.xml文件中添加mysql驱动依赖项 ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version><!--版本号根据实际情况而定--> </dependency> ``` 步骤二:编写代码连接mysql数据库,并执行操作 ```java public class JdbcTest { public static void main(String[] args) { String driver = "com.mysql.jdbc.Driver";//mysql驱动程序 String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8";//数据库连接地址 String username = "root";//用户名 String password = "root";//密码 Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { Class.forName(driver);//加载mysql驱动程序 connection = DriverManager.getConnection(url, username, password);//获取连接 statement = connection.createStatement();//创建statement对象 String sql = "SELECT * FROM student";//sql语句 resultSet = statement.executeQuery(sql);//执行查询操作 while (resultSet.next()) {//遍历结果集 int id = resultSet.getInt("id"); String name = resultSet.getString("name"); String sex = resultSet.getString("sex"); System.out.println(id + "\t" + name + "\t" + sex); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if(resultSet!=null){ resultSet.close();//关闭结果集 } if(statement!=null){ statement.close();//关闭statement对象 } if(connection!=null){ connection.close();//关闭连接 } } catch (SQLException e) { e.printStackTrace(); } } } } ``` 以上代码中,通过jdbc连接mysql数据库,获取连接后,使用`Statement`对象创建sql语句,并通过`executeQuery()`方法执行查询操作。最后使用`ResultSet`对象遍历结果集,输出结果。 总的来说,idea使用jdbc连接mysql数据库步骤非常简单,只需要按照以上步骤进行编写即可,这也是编写Java Web开发的基础知识之一。 ### 回答3: Idea是一款流行的Java IDE,它提供了JDBC连接MySQL数据库的功能。JDBCJava数据库连接的标准接口,它允许Java程序与各种各样的关系型数据库进行交互。MySQL是一款免费的开源数据库,在企业级应用和Web开发中广泛使用。 在Idea中连接MySQL数据库需要进行以下步骤: 1. 导入MySQL JDBC驱动 在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> ``` 或者在Idea中的Modules Setting中的Dependencies选项卡中手动导入。 2. 创建数据库连接Java代码中使用以下代码创建数据库连接: ```java Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName?useSSL=false&serverTimezone=UTC", "username", "password"); ``` 其中,com.mysql.cj.jdbc.Driver是MySQL 8.0版本的驱动类,localhost:3306是数据库的IP地址和端口号,DatabaseName是要连接数据库名称,username和password是数据库的用户名和密码。useSSL=false表示不使用SSL连接,serverTimezone=UTC表示使用UTC时区。 3. 使用SQL语句操作数据库 通过创建的Connection对象,可以使用Java代码执行SQL语句操作MySQL数据库,例如查询数据: ```java Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM TableName"); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); // ... } ``` 其中,TableName是要查询的表的名称,id和name是表中的列名。 4. 关闭连接使用数据库后,需要关闭Connection、Statement和ResultSet对象,例如: ```java rs.close(); stmt.close(); conn.close(); ``` 通过以上步骤,就可以在Idea中使用JDBC连接MySQL数据库了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值