使用JDBC连接MySQL数据库--典型案例分析(四)----更新和插入员工数据(四)

2015-07-24 11:31:38 · 作者: · 浏览: 13
{ System.out.println("释放资源时发生异常!"); } } } public void add(Emp emp){ Connection con=null; Statement stmt=null; int flag=-1; String sql="insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values("+emp.getEmpNo()+","+"'"+emp.getEname()+"',"+"'"+emp.getJob()+"',"+emp.getMgr()+","+"str_to_date('"+emp.getHiredate()+"','%Y-%m-%d %H:%i:%s'),"+emp.getSal()+","+emp.getComm()+","+emp.getDeptno()+")"; try { con=ConnectionSource.getConnection(); stmt=con.createStatement(); flag =stmt.executeUpdate(sql); //Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, //such as an SQL DDL statement. //either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 //for SQL statements that return nothing //这个flag返回有两种情况:1.返回执行完的行数 //如果是DDL语句那么什么都不返回。 //DDL语句:Data Definition Language //比如:CREATE DATABASE,CREATE TABLE,ALTER TABLE ,DROP TABLE,CREATE VIEW,ALTER VIEW ,DROP VIEW 等 if(flag>0){ System.out.println("新增记录成功!"); } } catch (SQLException e) { System.out.println("数据库访问异常!"); throw new RuntimeException(e); } finally{ try { if(stmt!=null){ stmt.close(); } if(con!=null){ con.close(); } } catch (SQLException e2) { System.out.println("释放资源发生异常!"); } } } public void update(Emp emp){ Connection con=null; Statement stmt=null; int flag=-1; String sql="update emp set sal="+emp.getSal()+","+"comm="+emp.getComm()+"where empno="+emp.getEmpNo(); try { con=ConnectionSource.getConnection(); stmt=con.createStatement(); flag=stmt.executeUpdate(sql); if(flag>0){ System.out.println("更新记录成功!"); } } catch (SQLException e) { System.out.println("数据库访问异常!"); throw new RuntimeException(e); }finally{ try { if(stmt!=null){ stmt.close(); } if(con!=null){ con.close(); } } catch (SQLException e2) { System.out.println("释放资源发生异常!"); } } } }

?

再次执行这个代码,会发生一异常,因为记录ID=1001的记录重复了。原因如下;

Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '1001' for key 'PRIMARY'

所以,我们我现在数据库里面把那条语句删掉,然后再次运行,这样子运行一把,就是刚刚创建了一个记录,然后就去再次对这个记录更新。控制台输出如下图所示:

\

再次,刷新数据库,如下图:

\

从运行结果可以看出,职员ID为1001的薪资被更新为4500.

完毕,下一次,准备研究研究用户名密码验证功能。尽请期待哦~


?