Viết SQLUtils
lớp có chứa static closeQuietly
các phương pháp bắt và ghi lại ngoại lệ như vậy, sau đó sử dụng khi thích hợp.
Bạn sẽ kết thúc với một cái gì đó mà đọc như thế này:
public class SQLUtils
{
private static Log log = LogFactory.getLog(SQLUtils.class);
public static void closeQuietly(Connection connection)
{
try
{
if (connection != null)
{
connection.close();
}
}
catch (SQLExcetpion e)
{
log.error("An error occurred closing connection.", e);
}
}
public static void closeQuietly(Statement statement)
{
try
{
if (statement!= null)
{
statement.close();
}
}
catch (SQLExcetpion e)
{
log.error("An error occurred closing statement.", e);
}
}
public static void closeQuietly(ResultSet resultSet)
{
try
{
if (resultSet!= null)
{
resultSet.close();
}
}
catch (SQLExcetpion e)
{
log.error("An error occurred closing result set.", e);
}
}
}
Và mã khách hàng của bạn sẽ được một cái gì đó như:
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try
{
connection = getConnection();
statement = connection.prepareStatement(...);
resultSet = statement.executeQuery();
...
}
finally
{
SQLUtils.closeQuietly(resultSet);
SQLUtils.closeQuietly(statment);
SQLUtils.closeQuietly(connection);
}
Nguồn
2009-08-26 16:06:05
Bạn có thể thấy rằng việc mua lại tài nguyên cũng như vậy. (Vì vậy, thực sự sử dụng câu trả lời của seth.) –