【JDBC】报错Exception in thread “main”com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communica

SQL写的没问题,JDBC的jar包也正常导入了,运行出现如下报错是因为数据库版本与jar包版本不一致

549f563826fd4c99aac54226060bf3f9.png

之前用的是5.1.47版本的jar包,而数据库却是MySQL8.0.11版本增差太大了导致无法驱动连接

导入新版本的jar包后添加到库中后就可以正常连接数据库了

324943587aba4a5d905612f9eea488f8.png

当成功连接数据库后有的人可能出现这样的警告

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。驱动程序'。这是不推荐的。新的驱动程序类是com.mysql.cj.jdbc.驱动程序。驱动程序通过SPI自动注册,通常不需要手动加载驱动程序类。

ebfd6a91666743cda69c8b3083f86df5.png

别急!我教你这样解决

首先这是一句警告,对程序运行没有任何影响 可以看到退出代码是0,这就说明程序成功执行了,但有些小伙伴有强迫症不想每次运行看到怎么办呢?

那直接按提示更新一下驱动就可以

Class.forName("com.mysql.cj.jdbc.Driver");

连接模板:

public static void main(String[] args) throws SQLException, ClassNotFoundException {
        //1.注册驱动
        Driver driver = new Driver();

        //2.得到链接
        String url = "jdbc:mysql://localhost:3306/pyq";
        //将用户名和密码放入到Properties对象
        Properties properties=new Properties();
        properties.setProperty("user","root");
        properties.setProperty("password","284650"); //自己设置的密码
        Connection connect = driver.connect(url, properties);

        //3.执行SQL
        String sql="insert into actor values(null,'彭于晏','男','2000-5-20','220')";
        Statement statement = connect.createStatement();
        int rows = statement.executeUpdate(sql);
 
        //4.关闭连接
        statement.close();
        connect.close();
    }

猜你喜欢

转载自blog.csdn.net/weixin_57535055/article/details/125290916