java - 调用 Class.forName() 而不保存对其返回的对象的引用的目的是什么?

标签 java sql class

在下面展示如何使用 Java 的 SQL 库的示例中,调用 Class.forName() 时不使用变量来保存对对象的引用。如果以后无法操纵的话,这样做的目的是什么?我在 SQL 库的各种示例中都看到过该行。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Sample
{
  public static void main(String[] args) throws ClassNotFoundException
  {
    // load the sqlite-JDBC driver using the current class loader
    Class.forName("org.sqlite.JDBC");

    Connection connection = null;
    try
    {
      // create a database connection
      connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
      Statement statement = connection.createStatement();
      statement.setQueryTimeout(30);  // set timeout to 30 sec.

      statement.executeUpdate("drop table if exists person");
      statement.executeUpdate("create table person (id integer, name string)");
      statement.executeUpdate("insert into person values(1, 'leo')");
      statement.executeUpdate("insert into person values(2, 'yui')");
      ResultSet rs = statement.executeQuery("select * from person");
      while(rs.next())
      {
        // read the result set
        System.out.println("name = " + rs.getString("name"));
        System.out.println("id = " + rs.getInt("id"));
      }
    }
    catch(SQLException e)
    {
      // if the error message is "out of memory", 
      // it probably means no database file is found
      System.err.println(e.getMessage());
    }
    finally
    {
      try
      {
        if(connection != null)
          connection.close();
      }
      catch(SQLException e)
      {
        // connection close failed.
        System.err.println(e);
      }
    }
  }
}

最佳答案

它使类初始值设定项运行 - 在 JDBC 驱动程序的情况下,这曾经是驱动程序将自身注册到 DriverManager 的方式。 。在现代 Java 中,通常使用 service provider 找到 JDBC 驱动程序。 API。

来自文档:

Applications no longer need to explictly load JDBC drivers using Class.forName(). Existing programs which currently load JDBC drivers using Class.forName() will continue to work without modification.

关于java - 调用 Class.forName() 而不保存对其返回的对象的引用的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477739/

相关文章:

java - 如何使Environment.getExternalStoragePublicDirectory()创建到SD卡的路径,而不是模拟/0(内部存储器)?

Java 代码总是返回错误消息(有效永远不等于 true)

sqlite - 将单列 SQL SELECT 结果列表变成一行

sql - PostgreSQL:结合这两个查询

bool 表达式中使用的 C++ 对象/类实例

python - “float/str/int”对象不可调用错误

java - Gradle 依赖项不包含在 jar 中

java - AdminTask.createDatasource 在 Dockerfile 中给出语法错误

sql - 两个表中具有多个共同属性的自然连接

c++ - 带有模板的类的构造方法