连接 java.sql.DriverManager
这是最简单的连接方式。
首先,驱动程序必须使用 java.sql.DriverManager
注册,以便它知道要使用哪个类。
这是通过加载驱动程序类来完成的,通常是。 java.lang.Class.forname( <driver class name> )
/**
* Connect to a PostgreSQL database.
* @param url the JDBC URL to connect to; must start with "jdbc:postgresql:"
* @param user the username for the connection
* @param password the password for the connection
* @return a connection object for the established connection
* @throws ClassNotFoundException if the driver class cannot be found on the Java class path
* @throws java.sql.SQLException if the connection to the database fails
*/
private static java.sql.Connection connect(String url, String user, String password)
throws ClassNotFoundException, java.sql.SQLException
{
/*
* Register the PostgreSQL JDBC driver.
* This may throw a ClassNotFoundException.
*/
Class.forName("org.postgresql.Driver");
/*
* Tell the driver manager to connect to the database specified with the URL.
* This may throw an SQLException.
*/
return java.sql.DriverManager.getConnection(url, user, password);
}
并非用户和密码也可以包含在 JDBC URL 中,在这种情况下,你不必在 getConnection
方法调用中指定它们。