(—)通過mysql workbench 創建一個數據庫,在這里命名為company,然后建一個tb_employee表
(二)以下是java代碼對表tb_employee的操作
1 創建一個Employee類,包括員工的一些信息,如 id name age sex
2創建DatabaseConnection類,用於數據庫的連接
3創建一個EmployeeOperation類,用於操作數據庫,它里面包括了 以下方法
(1)getInstance() //返回EmployeeOperation類實例的靜態方法
(2)saveEmployee(Employee emp) //向數據庫中加入數據
(3)selectEmployee() //從數據庫中查詢所需數據
(4)updateEmployee(Employee emp) //根據員工的編號更改員工的年齡信息
(5)deleteEmployeeById(Employee emp) //根據員工id刪除員工
4創建測試類
各個類的代碼如下
1 package 數據庫_向數據庫插入數據; 2 //盡量將屬性定義為私有的,寫出對應的setXXX和getXXX的方法 3 public class Employee { 4 private int empId; 5 private String empName; 6 private int empAge; 7 private String empSex; 8 9 public Employee(){} 10 11 public int getEmpId() { 12 return this.empId; 13 } 14 public void setEmpId(int id) { 15 this.empId = id; 16 } 17 18 public String getEmpName() { 19 return this.empName; 20 } 21 public void setEmpName(String name) { 22 this.empName = name; 23 } 24 25 public int getEmpAge() { 26 return this.empAge; 27 } 28 public void setEmpAge(int age) { 29 this.empAge = age; 30 } 31 32 public String getEmpSex() { 33 return this.empSex; 34 } 35 public void setEmpSex(String sex) { 36 this.empSex = sex; 37 } 38 39 }
1 package 數據庫_向數據庫插入數據; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 6 public class DatabaseConnection { 7 private static Connection conn = null; 8 public static Connection getCon() { 9 try { 10 Class.forName("com.mysql.jdbc.Driver"); //加載數據庫連接驅動 11 String user = "root"; 12 String psw = "XXX"; //XXX為自己的數據庫的密碼 13 String url = "jdbc:mysql://localhost:3306/ZZZ"; //ZZZ為連接的名字 14 conn = DriverManager.getConnection(url, user, psw); //獲取連接 15 } catch (Exception e) { 16 System.out.println("連接數據庫失敗"); 17 e.printStackTrace(); 18 } 19 return conn; 20 } 21 22 }
1 package 數據庫_向數據庫插入數據; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.ResultSet; 6 import java.sql.SQLException; 7 import java.sql.Statement; 8 import java.util.ArrayList; 9 import java.util.List; 10 11 //EmployeeOperation類用於操作數據庫,單例模式。 13 public class EmployeeOperation { 14 private static EmployeeOperation instance = new EmployeeOperation(); 15 16 public static EmployeeOperation getInstance() { 20 return instance; 21 } 22
private EmployeeOperation() {
} 23 public boolean saveEmployee(Employee emp) { //向數據庫中加入數據 24 boolean result = false; 25 Connection conn = null; 26 try { 27 28 conn = DatabaseConnection.getCon(); //建立數據庫連接 29 String sqlInset = "insert into company.tb_employee(empId, empName, empAge, empSex) values(?, ?, ?, ?)"; 30 PreparedStatement stmt = conn.prepareStatement(sqlInset); //會拋出異常 31 32 stmt.setInt(1, emp.getEmpId()); //設置SQL語句第一個“?”的值 33 stmt.setString(2, emp.getEmpName()); //設置SQL語句第二個“?”的值 34 stmt.setInt(3, emp.getEmpAge()); //設置SQL語句第三個“?”的值 35 stmt.setString(4, emp.getEmpSex()); //設置SQL語句第四個“?”的值 36 int i = stmt.executeUpdate(); //執行插入數據操作,返回影響的行數 37 if (i == 1) { 38 result = true; 39 } 40 } catch (SQLException e) { 41 // TODO Auto-generated catch block 42 e.printStackTrace(); 43 } finally { //finally的用處是不管程序是否出現異常,都要執行finally語句,所以在此處關閉連接 44 try { 45 conn.close(); //打開一個Connection連接后,最后一定要調用它的close()方法關閉連接,以釋放系統資源及數據庫資源 46 } catch(SQLException e) { 47 e.printStackTrace(); 48 } 49 } 50 51 return result; 52 53 } 54 55 56 public List<Employee> selectEmployee() { //從數據庫中查詢所需數據 57 List<Employee> empList = new ArrayList<Employee>(); 58 Connection conn = null; 59 try { 60 conn = DatabaseConnection.getCon(); 61 Statement stmt = conn.createStatement(); 62 ResultSet rs = stmt.executeQuery("select * from company.tb_employee");//執行SQL並返回結果集 63 while (rs.next()) { 64 Employee emp = new Employee(); 65 emp.setEmpId(rs.getInt("empId")); //從結果集rs中獲取內容時,若為字符串類型的,用rs.getString("string")方法 66 emp.setEmpName(rs.getString("empName")); //其中str為想要從 數據庫的 表 中獲取的信息 67 emp.setEmpAge(rs.getInt("empAge")); //若為int類型,用rs.getInt(number); 68 emp.setEmpSex(rs.getString("empSex")); 69 empList.add(emp); 70 } 71 } catch (Exception e) { 72 e.printStackTrace(); 73 } finally { 74 try { 75 conn.close(); //關閉連接 76 } catch (SQLException e) { 77 // TODO Auto-generated catch block 78 e.printStackTrace(); 79 } 80 } 81 return empList; //返回結果 82 } 83 84 85 public boolean updateEmployee(Employee emp) { //根據員工的編號更改員工的年齡信息 86 boolean result = false; 87 Connection conn = null; 88 try { 89 conn = DatabaseConnection.getCon(); 90 String sql = "update company.tb_employee set empAge=? where empId=?"; //update語句 91 PreparedStatement stmt = conn.prepareStatement(sql); 92 stmt.setInt(1, emp.getEmpAge()); //設置SQL語句第一個"?"的參數值 93 stmt.setInt(2, emp.getEmpId()); //設置SQL語句第二個"?"的參數值 94 int flag = stmt.executeUpdate(); //執行修改操作,返回影響的行數 95 if (flag == 1) { //修改成功返回true 96 result = true; 97 } 98 } catch(Exception e) { 99 e.printStackTrace(); 100 } finally { 101 try { 102 conn.close(); 103 } catch (SQLException e) { 104 // TODO Auto-generated catch block 105 e.printStackTrace(); 106 } 107 } 108 return result; 109 } 110 111 public boolean deleteEmployeeById(Employee emp) { 112 boolean result = false; 113 Connection conn = null; 114 try { 115 conn = DatabaseConnection.getCon(); 116 String sql = "delete from company.tb_employee where empId = ?"; 117 PreparedStatement stmt = conn.prepareStatement(sql); 118 stmt.setInt(1, emp.getEmpId()); 119 int i = stmt.executeUpdate(); 120 if (i == 1) { 121 result = true; 122 } 123 } catch (Exception e) { 124 e.printStackTrace(); 125 } finally { 126 try { 127 conn.close(); 128 } catch (SQLException e) { 129 // TODO Auto-generated catch block 130 e.printStackTrace(); 131 } 132 } 133 return result; 134 } 135 136 }
1 package 數據庫_向數據庫插入數據; 2 3 public class MainTest { 4 public static void main(String[] args) { //測試向數據庫的表中插入元素的方法 5 Employee emp = new Employee(); 6 emp.setEmpId(2); 7 emp.setEmpName("LILEI"); 8 emp.setEmpAge(33); 9 emp.setEmpSex("male"); 10 boolean res = EmployeeOperation.getInstance().saveEmployee(emp); 11 if (res == true) { 12 System.out.println("向company.tb_employee表中插入數據成功"); 13 } else { 14 System.out.println("向company.tb_employee表中插入數據失敗"); 15 } 16 } 17 18 }
1 package 數據庫_向數據庫插入數據; 2 3 import java.util.List; 4 5 public class SelectMainTest { //測試從數據庫中獲取數據的方法 6 public static void main(String[] args) { 7 List<Employee> empList = EmployeeOperation.getInstance().selectEmployee(); 8 System.out.println("員工ID\t員工姓名\t員工年齡\t員工性別"); 9 for (Employee emp : empList) { 10 System.out.print(emp.getEmpId() + "\t" + emp.getEmpName() + "\t" + emp.getEmpAge() + "\t" + emp.getEmpSex()); 11 System.out.println(); 12 } 13 } 14 15 }
1 package 數據庫_向數據庫插入數據; 2 3 import java.util.List; 4 5 public class UpdateMainTest { //根據員工的id修改員工年齡的方法 6 public static void main(String[] args) { 7 List<Employee> empList = EmployeeOperation.getInstance().selectEmployee(); 8 System.out.println("員工ID"); 9 for (Employee emp : empList) { 10 System.out.println(emp.getEmpId()); 11 } 12 Employee emp = new Employee(); 13 emp.setEmpId(2); 14 emp.setEmpAge(50); 15 boolean res = EmployeeOperation.getInstance().updateEmployee(emp); 16 if (res) { 17 System.out.println("編號為2的員工的年齡修改成功"); 18 } else { 19 System.out.println("編號為2的員工的年齡修改失敗"); 20 } 21 22 } 23 24 }
1 package 數據庫_向數據庫插入數據; 2 3 public class DeleteMainTest { 4 public static void main(String[] args) { //測試刪除對應id的員工的方法 5 Employee emp = new Employee(); 6 emp.setEmpId(1); 7 boolean res = EmployeeOperation.getInstance().deleteEmployeeById(emp); 8 if (res) { 9 System.out.println("成功刪除id為1的員工"); 10 } else { 11 System.out.println("未能成功刪除id為1的員工"); 12 } 13 } 14 15 }
以上代碼經個人親測,想要運行上述代碼的同學注意一下
1 DatabaseConnection類中用戶名和密碼要改一下,
2 在數據庫中建立的表的名字 以及表的各個列的名字需要一致
3 在JAVA工程中要引入 mysql-connector-java-5.1.34-bin.jar,如下圖所示