我无法连接到Pg Admin 4上的数据库;尽管能够使用intellij中的数据库浏览器查询数据库。以下是我不断收到的错误。
同一程序可以连接到数据库,但是在尝试下载python sql工具后出了点问题。我重新安装了postgresql并按原样创建了表,但现在无法连接到表。
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
这是尝试访问数据库的connectionclass.java。
public class ConnectionClass {
public Connection connection;
public Connection getConnection() {
String dbName = "users";
String userName = "postgres";
String password = "pass";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:5432/" + dbName, userName, password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
最后,我有了sql查询工具的屏幕截图。
我已经检查了数十种类似的错误,但它们似乎都包含拼写错误。我可以将数据库更改为不正确的名称,所有者或密码,但是错误仍然相同。我以为可能是驱动程序,因为我在程序中使用mysql-connector-java-8.0.20.jar,但运行数据库的是PostgreSQL。我尝试用postgresql-42.2.17.jar替换jar,但这也不起作用。
在这一点上,我正在考虑将整件事报废,并打算住在山上,以便能获得任何帮助。
编辑:将jar压缩到lib文件夹中将不起作用,除非您使用the method outlined here对其进行解压缩。可能需要尝试一些,但我的最终还是可以的。非常感谢!如果我有任何声望点,我会投票赞成。
答案 0 :(得分:1)
下载适当的驱动程序
https://jdbc.postgresql.org/download.html
像对mysql一样在程序中加载“正确的”驱动程序“ org.postgresql.Driver”,
Class.forName("org.postgresql.Driver");
并使用正确的协议“ jdbc:postgresql:”
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/" + dbName, userName, password);