Reputation: 15665
I'm following a tutorial and am looking at the following code:
package com.za.tutorial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class CreateDB {
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:zadb;create=true";
public static void main(String[] args) throws SQLException {
Connection connection = DriverManager.getConnection(JDBC_URL);
connection.createStatement().execute("create table channels (channel varchar(20), topic varchar(20),videoclip varchar(20))");
connection.createStatement().execute("insert into channels values " +
"('oodp', 'creational', 'singleton'), " +
"('oodp', 'creational', 'factory method'), " +
"('oodp', 'creational', 'abstract factory')");
System.out.println("channels table created and records successfully inserted...");
}
}
Why is this line being introduced?
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
The code works without it, and it doesn't appear to be referenced
Upvotes: 2
Views: 156
Reputation: 108961
In JDBC versions before JDBC 4 (Java 6) you needed to explicitly load a JDBC driver with Class.forName(...)
. In JDBC 4, automatic driver loading was introduced (assuming the driver supports it), which allows DriverManager
to automatically discover and load drivers on the initial class path. For details see How is driver class located in JDBC4.
The tutorial you use probably has an earlier version where it did load the driver explicitly, eg in the form of
public class CreateDB {
public static final String DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
public static final String JDBC_URL = "jdbc:derby:zadb;create=true";
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName(DRIVER);
Connection connection = DriverManager.getConnection(JDBC_URL);
connection.createStatement().execute("create table channels (channel varchar(20), topic varchar(20),videoclip varchar(20))");
connection.createStatement().execute("insert into channels values " +
"('oodp', 'creational', 'singleton'), " +
"('oodp', 'creational', 'factory method'), " +
"('oodp', 'creational', 'abstract factory')");
System.out.println("channels table created and records successfully inserted...");
}
}
It looks like the author of this tutorial removed the explicit loading of the driver but forgot to remove the constant. You can safely remove it, it isn't used in the code shown.
Be aware, loading drivers like this is still necessary in some circumstances.
Upvotes: 2