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