zoukankan      html  css  js  c++  java
  • JAVA对数据库进行操作,实现数据库中数据的插入,查询,更改,删除操作

    (—)通过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	员工姓名	员工年龄	员工性别");
     9         for (Employee emp : empList) {
    10             System.out.print(emp.getEmpId() + "	" + emp.getEmpName() + "	" + emp.getEmpAge() + "	" + 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,如下图所示

  • 相关阅读:
    js中两个==和三个===的区别
    软件需求工程解析
    《我们应当怎样做需求分析》阅读笔记
    需求工程阅读笔记03
    个人小软件冲刺05
    个人小软件冲刺04
    需求工程阅读笔记02
    个人小软件冲刺03
    个人小软件冲刺02
    个人小软件冲刺01
  • 原文地址:https://www.cnblogs.com/sodawoods-blogs/p/4415858.html
Copyright © 2011-2022 走看看