在下面展示如何使用 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 usingClass.forName()
will continue to work without modification.
关于java - 调用 Class.forName() 而不保存对其返回的对象的引用的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477739/