转换JDBC连接

时间:2013-02-22 09:29:00

标签: java jdbc

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

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;
            }


    }

2 个答案:

答案 0 :(得分:3)

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

org.forgerock.opendj.ldap.Connection 未延伸 java.sql.Connection

这应该为您提供更多信息,如Java中所允许的那样

答案 1 :(得分:1)

您无法使用JDBC API创建LDAP连接。您应该使用提供的org.forgerock.opendj.ldap API创建一个。

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

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

Getting OpenDJ LDAP SDK