2013-02-22 154 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