2013-04-16 77 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中阅读更多内容。