1. 在IDEA中,使用JDBC对stu表进行如下操作: 1. 添加一条记录: id = 4,name = 赵六,age = 37。 2. 修改记录:将王五的年纪修改为88岁。 3. 删除一条记录:删除李四所在行的记录。 4. 打印stu表的结果集。
时间: 2024-02-20 17:59:55 浏览: 73
好的,我来回答你的问题。
首先需要在IDEA中配置好数据库连接,这里假设数据库名为test,表名为stu,以MySQL为例。
1. 添加一条记录:
```java
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "password");
String sql = "INSERT INTO stu (id, name, age) VALUES (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 4);
pstmt.setString(2, "赵六");
pstmt.setInt(3, 37);
pstmt.executeUpdate();
pstmt.close();
conn.close();
```
2. 修改记录:
```java
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "password");
String sql = "UPDATE stu SET age = ? WHERE name = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, 88);
pstmt.setString(2, "王五");
pstmt.executeUpdate();
pstmt.close();
conn.close();
```
3. 删除一条记录:
```java
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "password");
String sql = "DELETE FROM stu WHERE name = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "李四");
pstmt.executeUpdate();
pstmt.close();
conn.close();
```
4. 打印stu表的结果集:
```java
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "password");
String sql = "SELECT * FROM stu";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
rs.close();
pstmt.close();
conn.close();
```
以上是使用JDBC对stu表进行添加、修改、删除和查询操作的代码示例。需要注意的是,在实际的开发过程中,需要进行异常处理、资源释放等操作,代码中只是简单示范。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![dta](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)