java - 自定义 JDBC 驱动程序

标签 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

最佳答案

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

关于java - 自定义 JDBC 驱动程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16027641/

相关文章:

mysql - Cognos 10.2.1 使用 JDBC 连接到 MySQL

java - 调用存储过程时,如何通过名称而不是其在 JDBC/JPA 中的位置来设置参数?

java - Java 可以看到我的键盘 Activity 吗?

java - 增加某个app的java堆空间

java - 如何在我的 Web 应用程序中拥有文本区域?

java - 如何使用正则表达式从字符串中提取时间?

Java : Io exception: The Network Adapter could not establish the connection

java - 应用服务器中是否有针对JDBC 的单点登录解决方案?

java - 测试对唯一标识符的查询是否最多返回一个结果

java - 使用自定义表模型从 JTable 中删除行