java对mysql进行查找替换_JAVA对数据库进行操作,实现数据库中数据的插入,查询,更改,删除操作...

这篇博客介绍了如何使用Java连接MySQL数据库,并实现对数据库中tb_employee表的增删查改操作。包括创建Employee类、DatabaseConnection类以及EmployeeOperation类,用于数据的插入、查询、更新和删除。测试类展示了这些操作的实际应用。
摘要由CSDN通过智能技术生成

(—)通过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 classEmployee {4 private intempId;5 privateString empName;6 private intempAge;7 privateString empSex;8

9 publicEmployee(){}10

11 public intgetEmpId() {12 return this.empId;13 }14 public void setEmpId(intid) {15 this.empId =id;16 }17

18 publicString getEmpName() {19 return this.empName;20 }21 public voidsetEmpName(String name) {22 this.empName =name;23 }24

25 public intgetEmpAge() {26 return this.empAge;27 }28 public void setEmpAge(intage) {29 this.empAge =age;30 }31

32 publicString getEmpSex() {33 return this.empSex;34 }35 public voidsetEmpSex(String sex) {36 this.empSex =sex;37 }38

39 }

1 package数据库_向数据库插入数据;2

3 importjava.sql.Connection;4 importjava.sql.DriverManager;5

6 public classDatabaseConnection {7 private static Connection conn = null;8 public staticConnection 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 returnconn;20 }21

22 }

1 package数据库_向数据库插入数据;2

3 importjava.sql.Connection;4 importjava.sql.PreparedStatement;5 importjava.sql.ResultSet;6 importjava.sql.SQLException;7 importjava.sql.Statement;8 importjava.util.ArrayList;9 importjava.util.List;10

11 //EmployeeOperation类用于操作数据库,单例模式。

13 public classEmployeeOperation {14 private static EmployeeOperation instance = new EmployeeOperation();15

16 public static EmployeeOperation getInstance() {20 returninstance;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 returnresult;52

53 }54

55

56 public List selectEmployee() { //从数据库中查询所需数据

57 List empList = new ArrayList();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 = newEmployee();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 returnresult;109 }110

111 public booleandeleteEmployeeById(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 returnresult;134 }135

136 }

1 package数据库_向数据库插入数据;2

3 public classMainTest {4 public static void main(String[] args) { //测试向数据库的表中插入元素的方法

5 Employee emp = newEmployee();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 importjava.util.List;4

5 public class SelectMainTest { //测试从数据库中获取数据的方法

6 public static voidmain(String[] args) {7 List 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 importjava.util.List;4

5 public classUpdateMainTest { //根据员工的id修改员工年龄的方法6 public static voidmain(String[] args) {7 List empList =EmployeeOperation.getInstance().selectEmployee();8 System.out.println("员工ID");9 for(Employee emp : empList) {10 System.out.println(emp.getEmpId());11 }12 Employee emp = newEmployee();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 classDeleteMainTest {4 public static void main(String[] args) { //测试删除对应id的员工的方法

5 Employee emp = newEmployee();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,如下图所示

931877165666cebec5327ca39ecd5b00.png

53ed1c0ef606f9baa15b8cb8b25ba136.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值