1. 在IDEA中,使用JDBC对stu表进行如下操作: 添加一条记录: id = 4,name = 赵六,age = 37。 修改记录:将王五的年纪修改为88岁。 删除一条记录:删除李四所在行的记录。定义Stu类 定义方法 public List<Stu> findAll(){} 实现方法 select * from stu;
时间: 2024-02-20 13:57:10 浏览: 56
好的,您的问题是如何使用JDBC对stu表进行增删改查操作,并且定义Stu类和实现findAll方法。下面是代码实现:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JDBCExample {
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USER = "root";
private static final String PASSWORD = "password";
public static void main(String[] args) {
// 添加一条记录
addRecord(4, "赵六", 37);
// 修改记录
updateRecord("王五", 88);
// 删除一条记录
deleteRecord("李四");
// 查询所有记录
List<Stu> stus = findAll();
for (Stu stu : stus) {
System.out.println(stu);
}
}
public static void addRecord(int id, String name, int age) {
String sql = "INSERT INTO stu (id, name, age) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, id);
ps.setString(2, name);
ps.setInt(3, age);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void updateRecord(String name, int age) {
String sql = "UPDATE stu SET age=? WHERE name=?";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, age);
ps.setString(2, name);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void deleteRecord(String name) {
String sql = "DELETE FROM stu WHERE name=?";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, name);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static List<Stu> findAll() {
List<Stu> stus = new ArrayList<>();
String sql = "SELECT * FROM stu";
try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
stus.add(new Stu(id, name, age));
}
} catch (SQLException e) {
e.printStackTrace();
}
return stus;
}
}
class Stu {
private int id;
private String name;
private int age;
public Stu(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Stu{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
在这个例子中,我们首先定义了一个JDBCExample类,其中包含了添加、修改、删除和查询方法。然后我们定义了一个Stu类来表示学生记录,并实现了一个findAll方法来查询所有学生记录。在每个JDBC操作中,我们都使用try-with-resources语句来自动关闭连接、语句和结果集。
阅读全文