java.lang.ClassCastException

用eclipse连接jdbc时,出现这个错误Exception in thread "main" java.lang.ClassCastException: class com.mysql.jdbc.JDBC4Connection cannot be cast to class com.atguigu.connection.Connection (com.mysql.jdbc.JDBC4Connection and com.atguigu.connection.Connection are in unnamed module of loader 'app'),这是什么导致的,怎么解决呢?请大佬指教

程序如下:

import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;

public class Connection {

@Test
public void testConnection1() throws SQLException {
    
    Driver driver = new com.mysql.jdbc.Driver();
    
    String url = "jdbc:mysql://localhost:3306/test";

    Properties info = new Properties();
    info.setProperty("user", "root");
    info.setProperty("password", "963.");
    
    Connection conn = (Connection) driver.connect(url, info);
    
    
    
    System.out.println(conn);
    
}

}

你的类型引用错了。

java.lang.ClassCastException: class com.mysql.jdbc.JDBC4Connection cannot be cast to class com.atguigu.connection.Connection (com.mysql.jdbc.JDBC4Connection and com.atguigu.connection.Connection are in unnamed module of loader 'app'),

jdbc和你自定义的connection类型冲突。

导包 import java.sql.Connection;

Connection conn,导错包了

你写的Connection 是你自己的测试类Connection不是MySQL驱动包的Connection

你看一下,应该是这个地方的返回值写错了:

img

driver.connect()方法的返回值,不是你自定义的返回值,所以,没有办法进行强制转换。
你先看看,是不是这个问题。

//你把 数据库的Connectiong 强转成了你的类Connection,
//自定义类应该尽量避免和 java自带的类同名
Connection conn = (Connection) driver.connect(url, info);