java - Connectivity issue with Postgresql using JDBC
问题描述
I have a legacy Java based web application which used Oracle 7. Now I'm migrating Oracle 7 to PostgreSQL. We had normal JDBC connectivity with Oracle as we didn't use any framework like Hibernate, iBATIS etc so we created connection, connection pool programmatically and used that. It works fine for Oracle DB.
But as part of migration, when I am changing with PostgreSQL details and trying to connect the DB with my application. At the first DB call only, connection is getting lost and in the logs I am seeing SQL:08003 issue. Since it is web based application so we are creating war and deploying it into apache-tomcat-8.5.50 server. PostgreSQL version is postgresql-42.2.18.jar.
I checked many blogs, but I'm not able to figure it out why this issue is occurring.
Code:
public DBConnection(String dbUrl, String user, char[] pwd) throws SQLException {
String errMsg = "Failed to get connection for login: " + user + " in URL = " + dbUrl;
try {
// Connect to database
mTheConnection = DriverManager.getConnection(dbUrl, user, new String(pwd));
if (mTheConnection == null) {
throw new SQLException (errMsg);
}
mTheConnection.setAutoCommit(false);
} catch (SQLException x) {
throw new SQLException(errMsg);
}
finally{
mTheConnection.close();
}
}
解决方案
这段代码显然永远无法工作——你关闭了finally
块中的连接。这个构造函数不可能完成一个正常工作的连接。
还要注意这样的事情:
} catch (SQLException x) {
throw new SQLException(errMsg);
}
总之就是傻。您正在获取非常有用的信息并将其丢弃,并用完全无用的信息替换它。如果您想将用户和 URL 信息添加到异常中(我不会在这里,它不太可能特别相关),请将您包装的异常作为原因 ( new SQLException(msg, x)
) 包含在内,以便您可以在那里看到数据。
SQLException 包含大量有用的信息。通过丢弃x
,您将无法看到所有这些有用的信息。
我们以编程方式创建了连接、连接池并使用了它。
上面的代码不是连接池。
DBConnection
Java 约定说你写DbConnection
. 此外,您不会对您的字段进行匈牙利标记(它是connection
,不是mTheConnection
)。
if (mTheConnection == null) {
这永远不可能发生;这是死代码。getConnection 不能返回 null。当然,在这种不太可能发生的情况下,您的代码会抛出该 SQLException,因此控制将移至 finally 块,在该块上close()
调用一个空引用,这会抛出一个 NPE,它会覆盖您的 SQLException(errMsg)。这段代码很乱。
我的建议?全部扔掉。获取HikariCP并使用它。
推荐阅读
- rest - 如何在 REST POST snaplogic 中传递正文参数?
- php - 卷曲登录+登录页面
- php - 带有部分文件名的 ftp_get() 文件(不是通配符)
- r - R - 读取大文件时如何处理“在输入连接上发现无效输入”警告?
- codenameone - 如何使用mirah为来自多个包的类创建映射器?
- android - 用户可以上传图片,即个人资料图片 - 有哪些最佳做法?
- go - 调用 eq 时出错:Go 模板中的比较类型无效
- r - 按物种、地点和日期绘制的不同直方图
- compiler-construction - LLVM IR 嵌套 phi 指令
- julia - 如何在 julia-0.7 中丢失所有缺失向量的平均值?