問題
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方法,代碼如下所示:
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表如下圖:

控制台輸出如下:

執行之後,刷新數據庫,如下圖;

通過上述執行結果,會發現在數據庫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 {
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("釋放資源發生異常!");
}
}
}
}
再次執行這個代碼,會發生一異常,因為記錄ID=1001的記錄重復了。原因如下;
Caused by: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '1001' for key 'PRIMARY'
所以,我們我現在數據庫裡面把那條語句刪掉,然後再次運行,這樣子運行一把,就是剛剛創建了一個記錄,然後就去再次對這個記錄更新。控制台輸出如下圖所示:

再次,刷新數據庫,如下圖:

從運行結果可以看出,職員ID為1001的薪資被更新為4500.
完畢,下一次,准備研究研究用戶名密碼驗證功能。盡請期待哦~