Gradle项目中使用JDBC驱动连接PostgreSQL报错:找不到合适驱动
问题排查与修复
1. 连接字符串包含多余引号(核心问题)
你的数据库连接字符串被额外的双引号包裹,导致JDBC无法识别正确的URL格式,这是触发错误的直接原因。
错误代码:
String jdbcConnectionString = "\"jdbc:postgresql://localhost:5432/test_stock_game\"";
修正后:
String jdbcConnectionString = "jdbc:postgresql://localhost:5432/test_stock_game";
2. 本地驱动依赖的文件名错误
手动配置依赖时,你漏掉了驱动jar包的.jar后缀,Gradle无法定位到正确的文件:
错误配置:
implementation files("libs/postgresql-42.5.2")
修正后(确保libs目录下的文件名为postgresql-42.5.2.jar):
implementation files("libs/postgresql-42.5.2.jar")
3. 推荐使用Maven Central自动依赖(更稳定)
手动管理jar包容易出现路径、文件名错误,建议直接启用Maven Central的依赖,注释掉本地文件依赖:
修正后的build.gradle依赖部分:
dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' implementation 'org.postgresql:postgresql:42.5.2' // implementation files("libs/postgresql-42.5.2.jar") }
额外提示
PostgreSQL 42.x版本属于JDBC4.2规范,通常不需要手动加载驱动类。如果问题仍存在,可在获取连接前显式添加驱动加载代码:
Class.forName("org.postgresql.Driver");
内容的提问来源于stack exchange,提问作者Kamil Tylus
相关产品推荐
相关产品推荐

