自定义JDBC驱动程序

时间:2013-04-16 02:11:48

标签: java jdbc

我正在编写自己的自定义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

2 个答案:

答案 0 :(得分: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 :(得分:1)

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

这是让DriverManager了解您的驱动程序的方法之一,请在DriverManager API中阅读更多内容。

相关问题