资源描述:
《Spring访问数据库异常的处理方法.doc》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、Spring访问数据库异常的处理方法来源:Javaeye博客 发布时间:2011-01-2220:45 阅读:134次 原文链接 全屏阅读 [收藏] 编辑点评:天我们将谈谈Spring访问数据库异常的处理方法,使用JDBCAPI时,很多操作都要声明抛出java.sql.SQLException异常,通常情况下是要制定异常处理策略。 使用JDBCAPI时,很多操作都要声明抛出java.sql.SQLException异常,通常情况下是要制定异常处理策略。而Spring的JDBC模块为我们提供了一套异常处理机制,这套异常系
2、统的基类是DataAccessException,它是RuntimeException的一种类型,那么就不用强制去捕捉异常了,Spring的异常体系如下: 目前为止我们还没有明确地处理Spring中JDBC模块的异常。要理解它的异常处理机制,我们来做几个测试。看下面的测试代码:1.publicvoidinsert(finalVehiclevehicle){2.Stringsql="insertintovehicle3.(ID,PLATE,CHASSIS,COLOR,WHEEL,SEAT)values4.(:id,:plate,:
3、chassis,:color,:wheel,:seat)";5.SqlParameterSourceparameterSource=newBeanPropertySqlParameterSource(6.vehicle);7.getSimpleJdbcTemplate().update(sql,parameterSource);8.}9.publicvoidinsert(finalVehiclevehicle){10.Stringsql="insertintovehicle(ID,PLATE,CHASSIS,COLOR,WHEEL
4、,SEAT)11.values(:id,:plate,:chassis,:color,:wheel,:seat)";12.SqlParameterSourceparameterSource=newBeanPropertySqlParameterSource(13.vehicle);14.getSimpleJdbcTemplate().update(sql,parameterSource);15.}publicstaticvoidmain(String[]args){ApplicationContextctx=newClassPat
5、hXmlApplicationContext("classpath:org/ourpioneer/vehicle/spring/applicationContext.xml");VehicleDAOvehicleDAO=(VehicleDAO)ctx.getBean("vehicleDAO");Vehiclevehicle=newVehicle("辽B-000000","1A00000001","RED",4,4);vehicle.setId(1);vehicleDAO.insert(vehicle);}publicstaticv
6、oidmain(String[]args){ApplicationContextctx=newClassPathXmlApplicationContext("classpath:org/ourpioneer/vehicle/spring/applicationContext.xml");VehicleDAOvehicleDAO=(VehicleDAO)ctx.getBean("vehicleDAO");Vehiclevehicle=newVehicle("辽B-000000","1A00000001","RED",4,4);veh
7、icle.setId(1);vehicleDAO.insert(vehicle);} 修改SQL语句,不使用自增主键的特性,并在这里设置重复的主键,那么运行程序,就会报出字段重复的异常。下面来捕捉这个异常:1.try{2.vehicleDAO.insert(vehicle);3.}catch(DataAccessExceptione){4.SQLExceptionsqle=(SQLException)e.getCause();5.System.out.println("Errorcode:"+sqle.getErrorCode(
8、));6.System.out.println("SQLstate:"+sqle.getSQLState());7.}8.try{9.vehicleDAO.insert(vehicle);10.}catch(DataAccessExceptione