【问题标题】:No suitable driver found for jdbc:postgresql://localhost:51020/university [duplicate]找不到适合 jdbc:postgresql://localhost:51020/university 的驱动程序 [重复]
【发布时间】:2019-10-06 22:29:11
【问题描述】:
import java.sql.*;
public class a2 {
  public static void main(String[] args) {
    try{
      Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/univ_db", "postgre", "astronaut.pd");
      PreparedStatement pstmt = con.prepareStatement("select id from student");
      ResultSet Rs = pstmt.executeQuery();
      while(Rs.next()){
        System.out.println(Rs.getInt(5));
      }
    }catch(Exception ex){
      System.out.println(ex.getMessage());
    }}}

我正在尝试将我的服务器与我的数据库连接,但我不知道我在这方面做错了什么。我尝试在网上搜索,但没有找到任何解决方案。

错误:

没有找到适合 jdbc:postgresql://localhost:5432/univ_db 的驱动

【问题讨论】:

  • 这与 SQL Server 有什么关系?这似乎与 Java 和 PostgreSQL 有关(与作为语言的 SQL 或 RDBMS SQL Server 无关)。我已经更新了这似乎与实际相关的标签。
  • 另外,该评论应该在您的问题中,而不是作为评论。我已经为您编辑了它,但请务必使用编辑功能。谢谢。
  • 由于我在 URL 本身中没有看到错误,这意味着您在运行应用程序时可能在类路径上没有 PostgreSQL JDBC 驱动程序。

标签: java postgresql jdbc


【解决方案1】:

要解决此错误,您需要在使用DriverManager.getConnection() 获取连接之前获取驱动程序类引用using Class.forName()

例子:

Class.forName(“org.postgresql.Driver”);

重要提示:记得将 postgree 驱动导入到你的 java 项目中。

【讨论】:

  • 自 2006 年以来,在使用 Java 6(假设 JDBC 4 或更高版本兼容的驱动程序)的简单 Java 应用程序中,这是不必要的,因为驱动程序会自动加载。 OP 更有可能在类路径上没有驱动程序。
猜你喜欢
  • 2021-12-05
  • 2018-11-30
  • 1970-01-01
  • 2022-09-26
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
相关资源
最近更新 更多