JAVA对数据库进行操作,实现数据库中数据的插入,查询,更改,删除操作

转载自:http://www.cnblogs.com/sodawoods-blogs/p/4415858.html

(—)通过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类用于操作数据库,以下的编写方法是JAVA软件编程的一种设计模式,称为!!!!! 单例模式,!!!!!!!
 12 //方法中先判断该类的对象是否为空,只有为空才创建(new) ,因此保证该对象在程序中永远是唯一的,可以避免重复创建对象造成的系统内存被过多占用
 13 public class EmployeeOperation {
 14     private static  EmployeeOperation instance = null;
 15     
 16     public static EmployeeOperation getInstance() { //返回EmployeeOperation类实例的静态方法,单例模式!!!!
 17         if (instance == null) {
 18             instance = new EmployeeOperation();
 19         }    
 20         return instance;
 21     }
 22     
 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 == true) {
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 == true) {
 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,如下图所示

大概就是这些,有错误的地方,请!拍!砖 !

 

 

发布了26 篇原创文章 · 获赞 4 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/y_onghuming/article/details/74558827