【问题标题】:custom JDBC driver自定义 JDBC 驱动程序
【发布时间】:2013-04-08 07:16:17
【问题描述】:

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

【问题讨论】:

  • Vitaly:我特别要求 JDBC,而不是自定义 URL 处理程序。我不清楚您提到的链接如何解决 DriverManager 引发的异常。
  • 顺便说一句,它现在工作了吗?
  • @JRR 您好,您成功实现了自己的 JDBC 驱动程序吗?你能分享你的代码吗?我也在尝试实现,但不幸被困在其中 - 或者如果它在你的 github 上 - 请分享 repo 链接。我会很感激的。提前非常感谢。
  • @JRR 你能告诉我如何编写自定义 jdbc 驱动程序吗?如果某处有很好的参考,请帮助我提供链接

标签: java jdbc


【解决方案1】:

你需要实现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;

【讨论】:

  • 这行得通。谢谢。我早些时候发布了一个答案,但它被删除了,我不知道为什么。以下是原文:原来它的工作方式是 DriverManager 将使用 URL 轮询每个已注册的驱动程序,并查看哪个会接受它(通过调用acceptURL),并在第一个在acceptURL 上返回true 的驱动程序上调用connect。
  • 太棒了!感谢您在确认后完成此问答。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    相关资源
    最近更新 更多