简体   繁体   中英

Implementing java 8 DriverAction Interface

I am running simple JDBC demo program where I used DriverAction interface and its deregister method to test its functionality, but I received error for my Dirver class, please find below code and suggest what is missing.

//error -com.mysql can not be resolve to type error

import java.sql.*;

public class Jdbcexample implements DriverAction {

    public static void main(String[] args) {
        try {
        Driver driver = new com.mysql.jdbc.Driver();/*com.mysql can not be resolve to type error */
        DriverAction driveraction = new Jdbcexample();
        DriverManager.registerDriver(driver,driveraction);
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
        Statement stmt =con.createStatement();
        ResultSet rs =stmt.executeQuery("select* from user");
        while(rs.next()) {
            System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
        }
        con.close();
    DriverManager.deregisterDriver(driver);
        }
        catch(Exception e) {
            System.out.println(e);
        }

}

    @Override
    public void deregister() {
        System.out.println("Driver is deregistered");

    }
}

The error itself means that you don't have a driver on the classpath when you're compiling your code. However the bigger problem is that you should not be doing this.

The DriverManager.registerDriver methods are not for user programs to call. They are for JDBC drivers to register themselves. The DriverManager.registerDriver(Driver, DriverAction) is a callback mechanism for the driver to do additional work when it is deregistered.

From the javadoc:

Registers the given driver with the DriverManager . A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager . If the driver is currently registered, no action is taken.

The important part is "A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager." .

And on DriverAction :

An interface that must be implemented when a Driver wants to be notified by DriverManager .

So, it is for JDBC drivers themselves, not for user programs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM