我通过 Postgres JDBC 驱动程序使用 Java 1.7 和 Postgres。数据库连接将从 Web 服务中使用。在测试中,我收到以下错误:
FATAL: connection limit exceeded for non-superusers
我通过使我的连接静态解决了这个错误,并且只创建了一次。我的问题是,静态连接安全吗?这是正确的方法吗?
我通过一个看起来像这样的 ConnectionFactory 使用连接:
public class ConnectionFactory
{
String driverClassName = "org.postgresql.Driver";
String connectionUrl = "jdbc:postgresql://localhost:5432/dbName";
String dbUser = "user";
String dbPwd = "password";
private static ConnectionFactory connectionFactory = null;
private static Connection conn = null;
private ConnectionFactory()
{
try
{
Class.forName(driverClassName);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
public Connection getConnection() throws SQLException
{
if (conn == null)
{
conn = DriverManager.getConnection(connectionUrl, dbUser, dbPwd);
}
return conn;
}
public static ConnectionFactory getInstance()
{
if (connectionFactory == null)
{
connectionFactory = new ConnectionFactory();
}
return connectionFactory;
}
}