Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom JDBC driver

Tags:

java

jdbc

I am writing my own custom JDBC driver. I am wondering how I can configure the URL prefix to be passed to DriverManager.getConnection in client code (i.e., the equivalent of jdbc:mysql when using mysql connector)? I seem to keep getting java.sql.SQLException: No suitable driver found. My code currently looks like the following:

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;
}

test code:

      Class.forName("CustomDriver");

      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection("customDriver://localhost/testdb"); 
      // throws SQLException
like image 765
JRR Avatar asked Aug 29 '26 09:08

JRR


2 Answers

You need to implement 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;
like image 78
Vitaly Avatar answered Aug 31 '26 22:08

Vitaly


Create a text file java.sql.Driverwith one line in it - fully qualified name of your driver. Put it in META-INF/services folder. In this case DriverManager will find and instatiate your driver and call acceptsURL(String url) on it.

This is one of the ways to let DriverManager know about your driver, read more in DriverManager API.

like image 25
Evgeniy Dorofeev Avatar answered Sep 01 '26 00:09

Evgeniy Dorofeev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!