连接 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);
}