【发布时间】:2016-11-07 10:32:07
【问题描述】:
我最近参加了一个编程挑战。公开一个用于管理虚构电影租赁公司的 API 是一个 OOP 挑战。我选择使用 sparkjava,并使用 heroku 模板。 I have posted the code to Github here,并邀请任何人查询 README 文档中提供的 URL。密码是secret。
我收到了很多关于需要改进的内容的良好反馈。一种反对意见是:
直接通过驱动程序处理连接,无需任何处理 正确关闭连接。
所以我想弄清楚这意味着什么,为什么会出现问题,以及如何解决它并使我的代码更好。
比如我有这个方法,in the main class:
public static int validate_customer(String cust) throws SQLException, URISyntaxException {
int customer = 0;
try{
customer = Integer.parseInt(cust);
}catch (Exception e){
throw new SQLException("Invalid customer integer -> " + cust);
}
Connection connection = DatabaseUrl.extract().getConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT count(*) from customers where id = ?;");
stmt.setInt(1, customer);
ResultSet rs = stmt.executeQuery();
rs.next();
if ( rs.getInt(1) < 1 ){
throw new SQLException("Invalid customer id -> " + customer);
}
rs.close();
stmt.close();
return customer;
}
为什么这是处理与数据库交互的错误方式?主类中还有其他与数据库交互的方法,但技术与本示例基本相同。
对我来说,如果与数据库的连接出现问题,它会出现在以下行:Connection connection = DatabaseUrl.extract().getConnection(); 并抛出 SQLException。如果连接发生问题,并且查询的某些部分不起作用,则此validate_customer 方法将引发异常。为什么这是我的代码中的问题?
【问题讨论】:
-
一个问题是您要么在不再需要连接时不关闭连接(例如,在出现异常的情况下,尤其是在连接本身断开的情况下),要么您可能过早关闭它(例如,如果您在该方法中调用
connection.close())。 -
@Thomas - 感谢您的帮助。使用连接池会解决这个问题吗?