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

时间:2022-07-07 13:10:13

转载请注明出处:http://blog.csdn.net/uniquewonderq

问题

1.更新和插入Emp数据

本案例要求使用JDBC想Emp表中插入和更新数据,详细要求如下:

1>.向Emp表中插入一条记录。其中为列 empno,enname,job,mgr,giredate,sal,comm,deptno的数据为1001,"rose","Analyst",7901,"2014-05-01",3000.00,500.00,10;

2>,更新职员ID为1001的薪资为4500

方案

Statement对象提供了executeUpdate()方法,该方法可以执行指定的sql语句,该语句可以是insert,update,delete。应用代码如下:

int result =stmt.executeUpdate(sql);

另外,我们在设计add方法时,该方法的参数是Emp类型,方法的声明如下:

public void add(Emp emp){}

之所以把Emp类作为add 方法的参数,是因为我们要保存的职员在Emp表的8个字段,也就是说有8项内容需要存入数据中。如果不用Emp类型作为add方法的参数类型,那么add方法将有8个参数,造成参数过多。对于数据库的表来说8个字段不算多,但是在企业中做项目的是时候,可能会有几十个字段的情况。所以使用对象封装方法参数是十分有必要的。另外,update方法的设计与add方法的设计类似。

Emp类是数据库表Emp和java实体类之间的映射,创建该类遵守一下规则:

1.如果类的成员变量的名字是xxx,那么为了更改或获取成员变量的值,即更改或获取属性的值,在类中可以使用getter或setter方法,方法的命名如下:

getXxx();用来获取属性xxx

setXxx();用来修改属性xxx

2.对于boolean类型的成员变量,即布尔逻辑类型的属性,允许使用"is"代替上述的“get”和“set”。

3.getter和setter方法必须是public的,因为外部要访问。

4.类中如果有构造方法,那么这个构造方法为public的并且是无参的。

步骤

步骤一:创建Emp类

该类为数据库表Emp与实体类之间的映射,代码如下所示:

package Entity;

public class Emp {
private int empNo;
private String ename;
private String job;
private int mgr;
private String hiredate;
private double sal;
private double comm;
private int deptno;
public Emp(){
super();
}
public Emp(int empNo,String ename,String job,int mgr,String hiredate,double sal,double comm,int deptno){
super();
this.empNo=empNo;
this.ename=ename;
this.job=job;
this.mgr=mgr;
this.hiredate=hiredate;
this.sal=sal;
this.comm=comm;
this.deptno=deptno;
}
public int getEmpNo() {
return empNo;
}
public void setEmpNo(int empNo) {
this.empNo = empNo;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public int getMgr() {
return mgr;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public String getHiredate() {
return hiredate;
}
public void setHiredate(String hiredate) {
this.hiredate = hiredate;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public double getComm() {
return comm;
}
public void setComm(double comm) {
this.comm = comm;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}

}
步骤二:在EmpDAO类中添加add方法

public void add(Emp emp){
}
步骤三
:拼写insert语句

在add方法中定义insert语句,代码如下所示:

public void add(Emp emp){
String sql="inset into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values("
+emp.getEmpNo()
+","
+"'"
+emp.getEname()
+"',"
+"'"
+emp.getJob()
+"',"
+emp.getMgr()
+","
+"to_date('"
+emp.getHiredate()
+"','yyyy-mm-dd'),"
+emp.getSal()
+","
+emp.getComm()+","+emp.getDeptno()+")";
}
}
步骤四:执行插入语句

首先创建数据库连接;然后通过连接创建Statement对象;最后使用Statement对象的updateExecute方法,执行插入语句并处理异常,代码如下所示:

public void add(Emp emp){
Connection con=null;
Statement stmt=null;
int flag=-1;
String sql="inset into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values("
+emp.getEmpNo()
+","
+"'"
+emp.getEname()
+"',"
+"'"
+emp.getJob()
+"',"
+emp.getMgr()
+","
+"to_date('"
+emp.getHiredate()
+"','yyyy-mm-dd'),"
+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("释放资源发生异常!");
}
}
}
步骤五:测试插入数据是否成功

在EmpDAO类的main方法中,调用add方法,代码如下所示:

<pre name="code" class="java">package dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import Entity.Emp;
public class EmpDAO {
public static void main(String [] args){
EmpDAO dao=new EmpDAO();
//1.select all
dao.findAll();
//2.insert
Emp emp=new Emp(1001,"rose","Analyst",7901,"2014-05-01",3000.00,500.00,10);
//System.out.println("emp.getEmpNo()"+emp.getEmpNo());
dao.add(emp);
//3.update
emp.setSal(4500.00);
dao.update(emp);
}
public void findAll(){
Connection con=null;
Statement stmt=null;
ResultSet rs=null;

try {
con=ConnectionSource.getConnection();
stmt=con.createStatement();
rs=stmt.executeQuery("select empno,ename,sal,hiredate from emp;");
while(rs.next()){
System.out.println(rs.getInt("empno")+","+rs.getString("ename")+","+rs.getDouble("sal")+","+rs.getDate("hiredate"));
}
} catch (SQLException e) {
System.out.println("数据库访问异常!");
throw new RuntimeException(e);
}
finally{
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(con!=null){
con.close();
}
} catch (SQLException e) {
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("释放资源发生异常!");
}
}
}
}


 
在执行 
执行上述代码之前,数据库Emp表如下图: 

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

控制台输出如下:

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

执行之后,刷新数据库,如下图;

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

通过上述执行结果,会发现在数据库Emp表中添加了一条员工ID为1001的记录。

步骤六:对Emp表中的数据执行更新

在EmpDAO类中,添加update方法,该方法实现将员工ID为1001的薪资更新为4500,代码如下所示:

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("释放资源发生异常!");
}
}
}
步骤七:测试update方法更新数据是否成功

代码如下所示

package dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;


import javax.management.RuntimeErrorException;


import Entity.Emp;
public class EmpDAO {
<span style="white-space:pre"></span>public static void main(String [] args){
<span style="white-space:pre"></span>EmpDAO dao=new EmpDAO();
<span style="white-space:pre"></span>//1.select all
<span style="white-space:pre"></span>dao.findAll();
<span style="white-space:pre"></span>//2.insert
<span style="white-space:pre"></span>Emp emp=new Emp(1001,"rose","Analyst",7901,"2014-05-01",3000.00,500.00,10);
<span style="white-space:pre"></span>//System.out.println("emp.getEmpNo()"+emp.getEmpNo());
<span style="white-space:pre"></span>dao.add(emp);
<span style="white-space:pre"></span>//3.update
<span style="white-space:pre"></span>emp.setSal(4500.00);
<span style="white-space:pre"></span>dao.update(emp);
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>public void findAll(){
<span style="white-space:pre"></span>Connection con=null;
<span style="white-space:pre"></span>Statement stmt=null;
<span style="white-space:pre"></span>ResultSet rs=null;
<span style="white-space:pre"></span>
<span style="white-space:pre"></span>try {
<span style="white-space:pre"></span>con=ConnectionSource.getConnection();
<span style="white-space:pre"></span>stmt=con.createStatement();
<span style="white-space:pre"></span>rs=stmt.executeQuery("select empno,ename,sal,hiredate from emp;");
<span style="white-space:pre"></span>while(rs.next()){
<span style="white-space:pre"></span>System.out.println(rs.getInt("empno")+","+rs.getString("ename")+","+rs.getDouble("sal")+","+rs.getDate("hiredate"));
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>} catch (SQLException e) {
<span style="white-space:pre"></span>System.out.println("数据库访问异常!");
<span style="white-space:pre"></span>throw new RuntimeException(e);
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>finally{
<span style="white-space:pre"></span>try {
<span style="white-space:pre"></span>if(rs!=null){
<span style="white-space:pre"></span>rs.close();
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>if(stmt!=null){
<span style="white-space:pre"></span>stmt.close();
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>if(con!=null){
<span style="white-space:pre"></span>con.close();
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>} catch (SQLException e) {
<span style="white-space:pre"></span>System.out.println("释放资源时发生异常!");
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>}


<span style="white-space:pre"></span>public void add(Emp emp){
<span style="white-space:pre"></span>Connection con=null;
<span style="white-space:pre"></span>Statement stmt=null;
<span style="white-space:pre"></span>int flag=-1;
<span style="white-space:pre"></span>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()+")";
<span style="white-space:pre"></span>try {
<span style="white-space:pre"></span>con=ConnectionSource.getConnection();
<span style="white-space:pre"></span>stmt=con.createStatement();
<span style="white-space:pre"></span>flag =stmt.executeUpdate(sql);
<span style="white-space:pre"></span>//Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing,
<span style="white-space:pre"></span>//such as an SQL DDL statement.
<span style="white-space:pre"></span>//either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0
<span style="white-space:pre"></span>//for SQL statements that return nothing
<span style="white-space:pre"></span>//这个flag返回有两种情况:1.返回执行完的行数
<span style="white-space:pre"></span>//如果是DDL语句那么什么都不返回。
<span style="white-space:pre"></span>//DDL语句:Data Definition Language
<span style="white-space:pre"></span>//比如:CREATE DATABASE,CREATE TABLE,ALTER TABLE ,DROP TABLE,CREATE VIEW,ALTER VIEW ,DROP VIEW 等
<span style="white-space:pre"></span>if(flag>0){
<span style="white-space:pre"></span>System.out.println("新增记录成功!");
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>} catch (SQLException e) {
<span style="white-space:pre"></span>System.out.println("数据库访问异常!");
<span style="white-space:pre"></span>throw new RuntimeException(e);
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>finally{
<span style="white-space:pre"></span>try {
<span style="white-space:pre"></span>if(stmt!=null){
<span style="white-space:pre"></span>stmt.close();
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>if(con!=null){
<span style="white-space:pre"></span>con.close();
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>} catch (SQLException e2) {
<span style="white-space:pre"></span>System.out.println("释放资源发生异常!");
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>}


<span style="white-space:pre"></span>public void update(Emp emp){
<span style="white-space:pre"></span>Connection con=null;
<span style="white-space:pre"></span>Statement stmt=null;
<span style="white-space:pre"></span>int flag=-1;
<span style="white-space:pre"></span>String sql="update emp set sal="+emp.getSal()+","+"comm="+emp.getComm()+"where empno="+emp.getEmpNo();
<span style="white-space:pre"></span>try {
<span style="white-space:pre"></span>con=ConnectionSource.getConnection();
<span style="white-space:pre"></span>stmt=con.createStatement();
<span style="white-space:pre"></span>flag=stmt.executeUpdate(sql);
<span style="white-space:pre"></span>if(flag>0){
<span style="white-space:pre"></span>System.out.println("更新记录成功!");
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>} catch (SQLException e) {
<span style="white-space:pre"></span>System.out.println("数据库访问异常!");
<span style="white-space:pre"></span>throw new RuntimeException(e);
<span style="white-space:pre"></span>}finally{
<span style="white-space:pre"></span>try {
<span style="white-space:pre"></span>if(stmt!=null){
<span style="white-space:pre"></span>stmt.close();
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>if(con!=null){
<span style="white-space:pre"></span>con.close();
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>} catch (SQLException e2) {
<span style="white-space:pre"></span>System.out.println("释放资源发生异常!");
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>}
}

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

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

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

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

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

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

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

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