2013-02-22 155 views
0

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

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

你正在创建通过MySQL驱动一个MySQL JDBC连接。你为什么会认为你会得到不同的东西? – 2013-02-22 09:30:41

+0

@BrianAgnew我不希望有任何不同于驱动程序中的com.mysql.jdbc.JDBC4Connection,我只是在寻找将其转换为org.forgerock.opendj.ldap.Connection类型的最佳方法。 – Glenn 2013-02-22 09:38:32

+1

所以铸造不是*转换*。而且我仍然怀疑你正在连接到MySQL数据库,并试图将其解释为LDAP服务器。 – 2013-02-22 09:52:06

回答

3

简短的回答,你不能.Heres为什么

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

因为什么在Java中

允许
+0

我假设你的意思是“'com.mysql.jdbc.JDBC4Connection'不会扩展'org.forgerock.opendj.ldap.Connection'”。现在写的你的陈述是完全错误的。 – 2013-02-22 09:51:52

+0

它不扩展ConnectionImpl,并* *实现连接? – 2013-02-22 09:53:26

+0

@Brian:由于org.forgerock.opendj.ldap.Connection是一个接口,它必须扩展java.sql。连接铸造工作 – Sudhakar 2013-02-22 10:07:48

1

不能使用JDBC API来创建一个LDAP连接这应该给你更多的信息。您应该使用提供的org.forgerock.opendj.ldap API创建一个。

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

查阅本指南,用于连接到LDAP服务器,并获得一种联系,你需要:

Getting OpenDJ LDAP SDK