2

我正在编写自己的自定义 JDBC 驱动程序。我想知道如何配置要DriverManager.getConnection在客户端代码中传递的 URL 前缀(即,在使用 mysql 连接器时相当于 jdbc:mysql )?我似乎不断得到java.sql.SQLException: No suitable driver found。我的代码目前如下所示:

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
4

2 回答 2

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;
于 2013-04-16T02:26:36.867 回答
2

创建一个java.sql.Driver包含一行的文本文件 - 驱动程序的完全限定名称。放在META-INF/services文件夹里。在这种情况下,DriverManager 将找到并实例化您的驱动程序并在其上调用acceptURL(String url)。

这是让 DriverManager 了解您的驱动程序的方法之一,请参阅 DriverManager API 了解更多信息。

于 2013-04-16T03:20:11.690 回答