0

我正在为一个项目开发一个新模块,该模块应该使用 JDBC 驱动程序连接到 SQL 数据库。我需要使用getConnection()返回类型的方法实现连接接口org.forgerock.opendj.ldap.Connection。但是,JDBC 驱动程序返回类型为 的连接com.mysql.jdbc.JDBC4Connection。铸造给了我以下错误:

Exception in thread "main" java.lang.ClassCastException: 
    com.mysql.jdbc.JDBC4Connection cannot be cast to org.forgerock.opendj.ldap.Connection
    at org.forgerock.opendj.virtual.JDBCConnectionFactory.getConnection(JDBCConnectionFactory.java:105)

获得类型连接org.forgerock.opendj.ldap.Connection而不是连接的最佳方法是com.mysql.jdbc.JDBC4Connection什么?

JDBCConnectionFactory 类:

public class JDBCConnectionFactory implements ConnectionFactory{
    private final String driverName = "com.mysql.jdbc.Driver";
    private Connection con = null;
    private String ConnectionUrl = "";
    private final String Host;
    private final int Port;
    private final String DbName;
    private final String UserName;
    private final String UserPass;

public JDBCConnectionFactory(final String host, final int port, final String dbName, final String userName, final String userPass) {
        this.Host = host;
        this.Port = port;
        this.DbName = dbName;
        this.UserName = userName;
        this.UserPass = userPass;
        this.ConnectionUrl="jdbc:mysql://"
                .concat(this.Host+":")
                .concat(this.Port+"/")
                .concat(this.DbName);

        try {
                Class.forName(driverName);
            } catch (ClassNotFoundException e) {
                System.out.println(e.toString());
            }
    }

getConnection 方法:

@Override
    public org.forgerock.opendj.ldap.Connection getConnection()throws ErrorResultException {
        try {

            con = DriverManager
                            .getConnection(this.ConnectionUrl,this.UserName,this.UserPass);

            org.forgerock.opendj.ldap.Connection newcon = (org.forgerock.opendj.ldap.Connection) con;
            System.out.println("Connection created.");
            return newcon;
            } catch (SQLException e) {
            System.out.println(e.toString());
            return null;
            }


    }
4

2 回答 2

3

简短的回答你不能。这就是为什么

org.forgerock.opendj.ldap.Connection 不延长 java.sql.Connection

这应该为您提供更多信息,因为 Java 允许

于 2013-02-22T09:46:50.173 回答
1

您不能使用 JDBC API 创建 LDAP 连接。您应该使用提供的org.forgerock.opendj.ldapAPI 创建一个。

您确定需要连接到 SQL 数据库而不是 LDAP 数据库吗?

查看本指南以连接到 LDAP 服务器并获得所需的连接类型:

获取 OpenDJ LDAP SDK

于 2013-02-22T10:13:01.310 回答