查询emp表,给工资低于1000的员工加上200的工资。工资高于或者等于1000的员工加上100的工资。

利用游标来做

以下是Java代码示例: ```java import java.sql.*; public class Main { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/emp"; static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(DB_URL, USER, PASS); stmt = conn.createStatement(); // 查询各部门平均工资 String sql = "SELECT deptno, AVG(sal) AS avg_sal FROM emp GROUP BY deptno"; ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { int deptno = rs.getInt("deptno"); double avg_sal = rs.getDouble("avg_sal"); // 更新低于部门平均工资员工工资 String sql2 = "UPDATE emp SET sal = sal + 100 WHERE deptno = " + deptno + " AND sal < " + avg_sal; int rows = stmt.executeUpdate(sql2); System.out.println(rows + " rows updated for deptno " + deptno); } rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } } } ``` 说明: 1. 首先通过 JDBC 连接到 MySQL 数据库 emp。 2. 查询 emp 中各部门的平均工资,使用 SQL GROUP BY 子句分组计算平均值。 3. 遍历查询结果,依次处理各部门的数据。 4. 对于每个部门,构建更新语句,使用 SQL WHERE 子句筛选出低于部门平均工资员工,并将他们的工资100元。 5. 执行更新语句,并输出更新的记录数。 6. 关闭数据库连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值