2
我得到以下錯誤不是每個數據庫查詢,但隨機與任何查詢約1%的概率。無論查詢是什麼,它都可以成功執行,然後在相同的查詢中失敗。奇怪的SQLException:找不到合適的驅動程序jdbc:postgresql
只有當我運行我的應用程序作爲tomcat web應用程序時纔會出現錯誤。單元測試或獨立應用程序模式(SpringApplication.run()
)不會失敗。
org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost
:5432/db_name
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:630)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:909)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:970)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:980)
at package.MyDBService.insert(MyDBService.java:32)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:postgresql://localhost:5432/db_name?tcpKeepAlive=true
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:120)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
... 15 more
如何我連接到DB
我用tomcat8和Spring。
@Configuration
public class JdbcFactory {
@Bean
public JdbcTemplate jdbcTemplate() {
Class.forName("org.postgresql.Driver");
return new JdbcTemplate(new DriverManagerDataSource("jdbc:postgresql://localhost:5432/db_name?tcpKeepAlive=true", "user", "pass"));
}
}
這是我典型的DAO看起來像
@Service
public class CommonDAO {
@Autowired JdbcTemplate jdbc;
public String getSome() {
return jdbc.query("...");
}
}
JDBC驅動程序作爲一個maven依賴提供。
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
沒有更多的其他DB連接配置。