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

===============>>#1 票数: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;

===============>>#2 票数:1

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

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

  ask by JRR translate from so

未解决问题?本站智能推荐: