【发布时间】:2015-03-10 12:39:22
【问题描述】:
我正在学习 Spring MVC Web 开发并使用 mysql 数据库。我在 here 找到了一个很好的例子,可以在 spring 中使用 DAO 连接 mysql。
当我测试我的代码时,它运行良好。我很想走得更远,我想到了 SQL Connection 异常。所以我尝试在没有运行 mysql 的情况下访问 sql 测试页面,但在该页面上出现 500 错误。我看到的例外是
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
如果是生产网站,谁能告诉我应该把try{} catch(){} 块放在哪里以避免这种情况?
我尝试自己将这些代码放在 MVC 配置类中
@Bean
public DataSource getDataSource() {
private DriverManagerDataSource dataSource;
try{
dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/contactdb");
dataSource.setUsername("root");
dataSource.setPassword("P@ssw0rd");
}
catch(Exception e){
System.out.println("Connection error.");
System.exit(0);
}
finally{
return dataSource;
}
}
但它不起作用所以任何人都可以帮助我并告诉我如何将它放入 try catch 块或更好的解决方案以避免此类错误?
提前谢谢你。
【问题讨论】:
标签: java mysql database spring spring-mvc