2013-04-16 4 views
2

내 자신의 JDBC 드라이버를 작성하고 있습니다. 나는 클라이언트 코드 (예 : mysql 커넥터를 사용할 때 jdbc : mysql과 동등)에서 DriverManager.getConnection에 전달할 URL 접두어를 어떻게 구성 할 수 있는지 궁금합니다. 나는 계속 java.sql.SQLException: No suitable driver found을 얻는 것처럼 보입니다.사용자 정의 JDBC 드라이버

static 
{ 
    try 
    { 
     CustomDriver driverInst = new CustomDriver(); 
     DriverManager.registerDriver(driverInst); 
    } 
    catch (Exception e) { e.printStackTrace(); } 
} 

public CustomDriver() throws SQLException 
{ 
    super(); 
} 

@Override 
public Connection connect (String url, Properties info) throws SQLException 
{ 
    // this is never called 
    return null; 
} 

테스트 코드 : 내 코드는 현재 다음과 같습니다 당신은 그것을 한 줄 텍스트 파일 java.sql.Driver 만들기 Driver.boolean acceptsURL(String url)

/** 
* Retrieves whether the driver thinks that it can open a connection 
* to the given URL. Typically drivers will return <code>true</code> if they 
* understand the subprotocol specified in the URL and <code>false</code> if 
* they do not. 
* 
* @param url the URL of the database 
* @return <code>true</code> if this driver understands the given URL; 
*   <code>false</code> otherwise 
* @exception SQLException if a database access error occurs 
*/ 
boolean acceptsURL(String url) throws SQLException; 
+1

중복 된 http://stackoverflow.com/questions/861500/url-to-load-resources-from-the-classpath-in-java 및 http://stackoverflow.com/questions/6278299/java-registering -custom-url-protocol-handlers – Vitaly

+0

Vitaly : 저는 맞춤 URL 처리기가 아닌 JDBC를 매우 특별하게 요구하고 있습니다. 언급 한 링크가 DriverManager에 의해 던져진 예외를 어떻게 해결할 수 있는지는 분명하지 않습니다. – JRR

+0

죄송합니다. – Vitaly

답변

3

- 자격을 갖춘 완전히 네 운전사 이름. META-INF/services 폴더에 넣으십시오. 이 경우 DriverManager는 드라이버를 찾고 인스턴스화하여 acceptsURL (String url)을 호출합니다.

이것은 DriverManager에 드라이버에 대한 정보를 제공하는 방법 중 하나입니다. 자세한 내용은 DriverManager API를 참조하십시오.

+1

이것은 효과가 있습니다. 감사. 나는 이전에 답변을 올렸지 만 삭제 되었기 때문에 그 이유를 모르겠습니다. 다음은 원래 텍스트입니다. DriverManager가 등록 된 각 드라이버를 URL로 폴링하고 어느 드라이버가 acceptsURL을 사용하는지 확인하고 (true), true를 반환하는 첫 번째 드라이버에서 connect를 호출합니다. acceptsURL. – JRR

+0

좋아요! 이 질문에 대한 답변을 확인해 주셔서 감사합니다. – Vitaly

1

를 구현해야

 Class.forName("CustomDriver"); 

     System.out.println("Connecting to database..."); 
     conn = DriverManager.getConnection("customDriver://localhost/testdb"); 
     // throws SQLException