1 public int insert(String user_id,String u_name,String u_pwd,String u_phone,String u_address,String u_sex,String u_birthday) throws Exception{ 2 String sql="insert into user(user_id,u_name,u_pwd,u_phone,u_address,u_sex,u_birthday)" +"values("+"‘"+user_id+"‘"+","+"‘"+u_pwd+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_address+"‘"+","+"‘"+u_sex+"‘"+","+"‘"+u_birthday+"‘"+")"; 3 st=connection.createStatement(); 4 int count=0; 5 count = st.executeUpdate(sql); 6 return count; 7 }
上面这段代码,发生异常后直接抛出给上一级处理,而上一级又抛出给上一级,最后,导致这个异常没有被处理,所以程序代码没有继续执行下去
此次在做数据库课设中,在插入数据时,特意测试一下插入失败的结果,发现自己代码中 异常处理的一些问题。
如上述代码为改正后的代码,插入失败后,发生异常后catch语句捕获处理,程序可以继续执行。代码如下
public int insert(String user_id,String u_name,String u_pwd,String u_phone,String u_address,String u_sex,String u_birthday){ String sql="insert into user(user_id,u_name,u_pwd,u_phone,u_address,u_sex,u_birthday)" +"values("+"‘"+user_id+"‘"+","+"‘"+u_pwd+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_phone+"‘"+","+"‘"+u_address+"‘"+","+"‘"+u_sex+"‘"+","+"‘"+u_birthday+"‘"+")"; try { st=connection.createStatement(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } int count=0; try { count = st.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; }