連線 java.sql.DriverManager 和 Properties
你可以將它們打包到 java.util.Properties
物件中,而不是在 URL 或單獨的引數中指定使用者和密碼等連線引數(請參閱此處的完整列表 )。
/**
* 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");
java.util.Properties props = new java.util.Properties();
props.setProperty("user", user);
props.setProperty("password", password);
/* don't use server prepared statements */
props.setProperty("prepareThreshold", "0");
/*
* Tell the driver manager to connect to the database specified with the URL.
* This may throw an SQLException.
*/
return java.sql.DriverManager.getConnection(url, props);
}