gpt4 book ai didi

java - 如何使用从表中选择数据,进行计算,然后将新数据更新到与第一个主键相同的另一个表中?

转载 作者:行者123 更新时间:2023-11-29 11:24:27 25 4
gpt4 key购买 nike

我正在使用 java servlet 来执行以下操作:

我有一个名为 Table1 的表,其中包含两列:“EmployeeID(主键)”和“毛工资”

我有另一个名为 Table2 的表,其中有两列:“EmployeeID(主键)”和“净工资”

数据库中当前有许多员工 ID。

如何从表 1 中检索所有员工的毛工资,进行计算以计算净工资,然后将新值(计算后)插入到表 2 中每位员工的相应行中的净工资中?

这是我到目前为止所拥有的,甚至可能没有走上正确的轨道,感谢帮助,谢谢。

顺便说一句,如果你们中有人可以用计算部分来证明答案,为了便于论证,以 netSalary =grossSalary - 100 为例。

 Class.forName("com.mysql.jdbc.Driver").newInstance(); 
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("SELECT Gross salary from payroll_system.Table1");
ps.executeUpdate();

最佳答案

首先,您需要执行查询,而不是更新,然后将数据保存在 HashMap 中,最后执行计算并插入结果:

    ResultSet rs = ps.executeQuery(selectSQL );
Map<Integer, Float> grossSalaries = new HashMap<>();
Map<Integer, Float> netSalaries = new HashMap<>();
while (rs.next()) {
grossSalaries.put(rs.getInt(1), rs.getFloat(2));
}
//Do the calculations for each one of the elements in the map
//Save them into the netSalaries Map.

//Then insert the rows in the Table2
for(Integer key : netSalaries.keySet){
String insertSt = "insert into Table2 values (?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertSt);
preparedStatement.setInt(1, key);
preparedStatement.setFloat(2, netSalaries.get(key));
}

关于java - 如何使用从表中选择数据,进行计算,然后将新数据更新到与第一个主键相同的另一个表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38469586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com