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

时间:2023-12-26 14:30:25

(—)通过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创建测试类

各个类的代码如下

 package 数据库_向数据库插入数据;
//尽量将属性定义为私有的,写出对应的setXXX和getXXX的方法
public class Employee {
private int empId;
private String empName;
private int empAge;
private String empSex; public Employee(){} public int getEmpId() {
return this.empId;
}
public void setEmpId(int id) {
this.empId = id;
} public String getEmpName() {
return this.empName;
}
public void setEmpName(String name) {
this.empName = name;
} public int getEmpAge() {
return this.empAge;
}
public void setEmpAge(int age) {
this.empAge = age;
} public String getEmpSex() {
return this.empSex;
}
public void setEmpSex(String sex) {
this.empSex = sex;
} }
 package 数据库_向数据库插入数据;

 import java.sql.Connection;
import java.sql.DriverManager; public class DatabaseConnection {
private static Connection conn = null;
public static Connection getCon() {
try {
Class.forName("com.mysql.jdbc.Driver"); //加载数据库连接驱动
String user = "root";
String psw = "XXX"; //XXX为自己的数据库的密码
String url = "jdbc:mysql://localhost:3306/ZZZ"; //ZZZ为连接的名字
conn = DriverManager.getConnection(url, user, psw); //获取连接
} catch (Exception e) {
System.out.println("连接数据库失败");
e.printStackTrace();
}
return conn;
} }
 package 数据库_向数据库插入数据;

 import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List; //EmployeeOperation类用于操作数据库,单例模式。
public class EmployeeOperation {
private static EmployeeOperation instance = new EmployeeOperation(); public static EmployeeOperation getInstance() { return instance;
}

     private EmployeeOperation() {
}
public boolean saveEmployee(Employee emp) { //向数据库中加入数据
boolean result = false;
Connection conn = null;
try { conn = DatabaseConnection.getCon(); //建立数据库连接
String sqlInset = "insert into company.tb_employee(empId, empName, empAge, empSex) values(?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(sqlInset); //会抛出异常 stmt.setInt(1, emp.getEmpId()); //设置SQL语句第一个“?”的值
stmt.setString(2, emp.getEmpName()); //设置SQL语句第二个“?”的值
stmt.setInt(3, emp.getEmpAge()); //设置SQL语句第三个“?”的值
stmt.setString(4, emp.getEmpSex()); //设置SQL语句第四个“?”的值
int i = stmt.executeUpdate(); //执行插入数据操作,返回影响的行数
if (i == 1) {
result = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally { //finally的用处是不管程序是否出现异常,都要执行finally语句,所以在此处关闭连接
try {
conn.close(); //打开一个Connection连接后,最后一定要调用它的close()方法关闭连接,以释放系统资源及数据库资源
} catch(SQLException e) {
e.printStackTrace();
}
} return result; } public List<Employee> selectEmployee() { //从数据库中查询所需数据
List<Employee> empList = new ArrayList<Employee>();
Connection conn = null;
try {
conn = DatabaseConnection.getCon();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from company.tb_employee");//执行SQL并返回结果集
while (rs.next()) {
Employee emp = new Employee();
emp.setEmpId(rs.getInt("empId")); //从结果集rs中获取内容时,若为字符串类型的,用rs.getString("string")方法
emp.setEmpName(rs.getString("empName")); //其中str为想要从 数据库的 表 中获取的信息
emp.setEmpAge(rs.getInt("empAge")); //若为int类型,用rs.getInt(number);
emp.setEmpSex(rs.getString("empSex"));
empList.add(emp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close(); //关闭连接
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return empList; //返回结果
} public boolean updateEmployee(Employee emp) { //根据员工的编号更改员工的年龄信息
boolean result = false;
Connection conn = null;
try {
conn = DatabaseConnection.getCon();
String sql = "update company.tb_employee set empAge=? where empId=?"; //update语句
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, emp.getEmpAge()); //设置SQL语句第一个"?"的参数值
stmt.setInt(2, emp.getEmpId()); //设置SQL语句第二个"?"的参数值
int flag = stmt.executeUpdate(); //执行修改操作,返回影响的行数
if (flag == 1) { //修改成功返回true
result = true;
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
} public boolean deleteEmployeeById(Employee emp) {
boolean result = false;
Connection conn = null;
try {
conn = DatabaseConnection.getCon();
String sql = "delete from company.tb_employee where empId = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1, emp.getEmpId());
int i = stmt.executeUpdate();
if (i == 1) {
result = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
} }
 package 数据库_向数据库插入数据;

 public class MainTest {
public static void main(String[] args) { //测试向数据库的表中插入元素的方法
Employee emp = new Employee();
emp.setEmpId(2);
emp.setEmpName("LILEI");
emp.setEmpAge(33);
emp.setEmpSex("male");
boolean res = EmployeeOperation.getInstance().saveEmployee(emp);
if (res == true) {
System.out.println("向company.tb_employee表中插入数据成功");
} else {
System.out.println("向company.tb_employee表中插入数据失败");
}
} }
 package 数据库_向数据库插入数据;

 import java.util.List;

 public class SelectMainTest {     //测试从数据库中获取数据的方法
public static void main(String[] args) {
List<Employee> empList = EmployeeOperation.getInstance().selectEmployee();
System.out.println("员工ID\t员工姓名\t员工年龄\t员工性别");
for (Employee emp : empList) {
System.out.print(emp.getEmpId() + "\t" + emp.getEmpName() + "\t" + emp.getEmpAge() + "\t" + emp.getEmpSex());
System.out.println();
}
} }
 package 数据库_向数据库插入数据;

 import java.util.List;

 public class UpdateMainTest {    //根据员工的id修改员工年龄的方法
public static void main(String[] args) {
List<Employee> empList = EmployeeOperation.getInstance().selectEmployee();
System.out.println("员工ID");
for (Employee emp : empList) {
System.out.println(emp.getEmpId());
}
Employee emp = new Employee();
emp.setEmpId(2);
emp.setEmpAge(50);
boolean res = EmployeeOperation.getInstance().updateEmployee(emp);
if (res) {
System.out.println("编号为2的员工的年龄修改成功");
} else {
System.out.println("编号为2的员工的年龄修改失败");
} } }
 package 数据库_向数据库插入数据;

 public class DeleteMainTest {
public static void main(String[] args) { //测试删除对应id的员工的方法
Employee emp = new Employee();
emp.setEmpId(1);
boolean res = EmployeeOperation.getInstance().deleteEmployeeById(emp);
if (res) {
System.out.println("成功删除id为1的员工");
} else {
System.out.println("未能成功删除id为1的员工");
}
} }

以上代码经个人亲测,想要运行上述代码的同学注意一下

1 DatabaseConnection类中用户名和密码要改一下,

2 在数据库中建立的表的名字 以及表的各个列的名字需要一致

3 在JAVA工程中要引入 mysql-connector-java-5.1.34-bin.jar,如下图所示

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

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