JDBC连接mysql中出现的问题

版权声明:本文为博主原创文章,转载请附上博文链接! https://blog.csdn.net/f2764052703/article/details/89432511

首先说一说我的环境

win10企业版 + Java 8 + MySQL8.0

然后说一说在连接mysql的时候出现的问题

  1. MySQL 5.x 和 MySQL 8.x使用的驱动类不太一样

    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这个驱动类在MySQL 8.0的版本中已经更新了,现在加载驱动的时候需要使用com.mysql.cj.jdbc.Driver这个驱动类。

    当然了,我试过,使用 com.mysql.jdbc.Driver这个驱动类仍然可以连接数据库,但是之后会出现什么问题尚且不太清楚,可能会打开一个潘多拉魔盒,也可能会无缝衔接。。。。

  2. MySQL时区出现了问题
    问题:The server time zone value ‘Öйú±ê׼ʱ¼ä’ is unrecognized or represents more than one time zone…

    具体报错信息已经失踪

    解决方法:更改MySQL时区
    命令:

    show variables like '%time_zone%';
    set global time_zone='+8:00';
    

最后,附上连接数据库的代码:

package com.stu.jdbc;

import java.sql.*;

public class JdbcTest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {

        // 1、加载mysql驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 2、连接mysql数据库
        String url = "jdbc:mysql://localhost:3306/stu?useUnicode=true&characterEncoding=utf8&useSSL=true";  // 连接mysql的协议
        String user = "root";    // 数据库的用户名
        String pwd = "root";     // 数据库的密码
        Connection connection = DriverManager.getConnection(url,user,pwd);

        if(!connection.isClosed())
            System.out.println("database already connection...........");
        else
            System.out.println("database hasn`t connetction.........");

        // 3、得到一个Statement对象,Statement是一个用于执行静态 SQL 语句并返回它所生成结果的对象
        Statement st = connection.createStatement();

        // 写SQL语句
        String addSql = "insert into user(username,password) values ('小紫','sdfsd')";

        // 执行SQL语句并得到结果
        int i = st.executeUpdate(addSql);
        if(i != 0){
            System.out.println("插入成功");
        }
        
        String selectSql = "select * from stu";
        ResultSet se = st.executeQuery(selectSql);
    }
}

猜你喜欢

转载自blog.csdn.net/f2764052703/article/details/89432511