2013-04-16 76 views
2

我正在編寫自己的自定義JDBC驅動程序。我想知道如何將客戶端代碼中的URL前綴配置爲DriverManager.getConnection(即使用mysql連接器時等同於jdbc:mysql)?我似乎不斷得到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; 
} 

測試代碼:

 Class.forName("CustomDriver"); 

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

http://stackoverflow.com/questions/861500/url-to-load-resources-from-the-classpath-in-java和http://stackoverflow.com/questions/6278299/java-registering - 自定義url的協議處理程序 – Vitaly

+0

Vitaly:我非常專門問JDBC,而不是一個自定義的URL處理程序。我不清楚你提到的鏈接如何解決DriverManager拋出的異常。 – JRR

+0

對不起,回答。 – Vitaly

回答

3

您需要實現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

這工作。謝謝。我之前發佈了一個答案,但它被刪除了,我不知道爲什麼。這是原始文本: 原因是DriverManager將輪詢每個已註冊驅動程序的URL並查看哪一個會接受它(通過calledURLURL),並將在第一個返回true的驅動程序上調用connect acceptsURL。 – JRR

+0

太棒了!感謝您提出這個問題 - 回答完成您的確認。 – Vitaly

1

創建一個文本文件java.sql.Driver與上一行 - 完全合格你司機的名字。把它放在META-INF/services文件夾中。在這種情況下,DriverManager將查找並安裝驅動程序並在其上調用acceptURL(String url)。

這是讓DriverManager知道您的驅動程序的方法之一,請在DriverManager API中閱讀更多內容。