为什么要设置字符串DRIVER?

时间:2018-06-14 19:07:51

标签: java sql jdbc

我正在关注教程并正在查看以下代码:

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...");

    }
}

为什么会引入这条线?

public static final String DRIVER =  "org.apache.derby.jdbc.EmbeddedDriver";

代码在没有它的情况下工作,似乎没有被引用

1 个答案:

答案 0 :(得分:2)

在JDBC 4(Java 6)之前的JDBC版本中,您需要使用Class.forName(...)显式加载JDBC驱动程序。在JDBC 4中,引入了自动驱动程序加载(假设驱动程序支持它),这允许DriverManager在初始类路径上自动发现和加载驱动程序。有关详细信息,请参阅How is driver class located in JDBC4

您使用的教程可能有一个早期版本,它确实明确地加载了驱动程序,例如以

的形式
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...");
    }
}

看起来本教程的作者删除了驱动程序的显式加载但忘记删除常量。您可以安全地删除它,它不会在显示的代码中使用。

请注意,在某些情况下,仍然需要加载此类驱动程序。