0

I know about 2 ways to connect to database well I will divided it into 2 methods (Method1 and Method 2)

Connection connection;

public void getConnectionMethod1() {
    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        connection = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/latihan","sa","denni");
    } catch (SQLException e) {
    }
}

public void getConnectionMethod2() {
    try {
        DriverManager.registerDriver(new net.sourceforge.jtds.jdbc.Driver());
        connection = DriverManager.getConnection("jdbc:jtds:sqlserver://localhost:1433/latihan","sa","denni");
    } catch (SQLException e) {
    }
}

My question is; is there any difference between them ? Method 1 uses Class.forName While method 2 uses registerDriver

What is the advantages and disadvantages between them?

NOTE : I can only use PreparedStatement on Method 2.

Sjon
  • 4,989
  • 6
  • 28
  • 46
Denni S
  • 134
  • 1
  • 15
  • 2
    JDBC has not needed either of those for a long time now. Just calling DriverManager.getConnection is sufficient. – VGR Oct 27 '15 at 17:43
  • VGR is correct. All newer JDBC drivers will auto-register. This is done by the file `META-INF/services/java.sql.Driver` in the driver .jar file. If you driver.jar file has this entry, you don't need either method. If it doesn't, you should consider upgrading to a newer version of the driver. – Andreas Oct 27 '15 at 17:46
  • 3
    http://stackoverflow.com/questions/5484227/jdbc-class-forname-vs-drivermanager-registerdriver – SatyaTNV Oct 27 '15 at 17:47
  • As for your question, the main difference is that method 2 requires the driver to be present at compile-time. – Andreas Oct 27 '15 at 17:47

1 Answers1

2

From JDBC 4.0,Java developers no longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver. The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.