public long insert(String sql, Object... args) {
long id = 0;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
connection = ConnectionContext.getInstance().get();
//connection=JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
if(args != null){
for(int i = 0; i < args.length; i++){
preparedStatement.setObject(i + 1, args[i]);
}
}
preparedStatement.executeUpdate();
resultSet=preparedStatement.getGeneratedKeys();
if(resultSet.next()){
id=resultSet.getLong(1);
}
}catch(Exception e)
{
e.printStackTrace();
}finally{
JDBCUtils.release(resultSet,preparedStatement);
}
return id;
}
因为SQLException只能捕获sql方面产生的问题,而空指针一次不是在sqlexcotion下面,所以会报空指针异常,Exception可以捕获所有的异常,所以能捕获空指针,所有的异常捕获的接口和类都要继承或实现Exception
Exception包含了SQLException和空指针异常。是它们的父类。SQLException和空指针异常是可以写在并排。
在Java 7中,我们可以用一个catch块捕获所有这些异常:
eg:
catch(IOException | SQLException | Exception ex){
logger.error(ex);
throw new MyException(ex.getMessage());
}
SQLException只捕捉SQL方面的异常,而Exception可以捕捉所有异常。
Exception是SQLException的父类,NullPointerException是RuntimeException的直接子类,RuntimeException是Exception的直接子类
捕捉异常的包含关系,