借助JDBC在库名tsgc中完成对数据表employee中性别为“女”的员工密码修改为“hello”
时间: 2024-03-25 13:39:09 浏览: 17
好的,以下是Java JDBC实现你所需功能的示例代码:
```java
import java.sql.*;
public class Main {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/tsgc";
String user = "root";
String password = "123456";
Connection conn = null;
Statement stmt = null;
try {
// 1. 注册 JDBC 驱动器
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. 打开一个连接
conn = DriverManager.getConnection(url, user, password);
// 3. 执行 SQL 查询
stmt = conn.createStatement();
String sql = "UPDATE employee SET e_password='hello' WHERE e_gender='女'";
int rowsAffected = stmt.executeUpdate(sql);
// 4. 处理查询结果
System.out.println("成功修改 " + rowsAffected + " 条记录。");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 5. 关闭连接和释放资源
try {
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在上述示例代码中,我们使用了Java的JDBC API,通过执行SQL语句实现了对数据库中employee表中性别为“女”的员工密码修改为“hello”的操作。需要注意的是,实际应用中需要根据具体的数据库连接信息和表结构进行适当调整。