Java增删改查功能实现代码
时间: 2024-10-24 19:07:30 浏览: 17
在Java中,数据库操作通常通过JDBC(Java Database Connectivity)连接和SQL查询来实现增删改查的功能。这里给出一个简单的例子,假设我们有一个名为"Student"的实体类,代表学生表,包含id、name和age属性:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class CRUDOperations {
private static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASS = "password";
// 创建一个新的学生
public void insert(Student student) {
String sql = "INSERT INTO students (name, age) VALUES (?, ?)";
try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, student.getName());
statement.setInt(2, student.getAge());
statement.executeUpdate();
} catch (Exception e) {
System.out.println("Error inserting data: " + e.getMessage());
}
}
// 更新学生信息
public void update(Student student) {
String sql = "UPDATE students SET name = ?, age = ? WHERE id = ?";
try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setString(1, student.getName());
statement.setInt(2, student.getAge());
statement.setInt(3, student.getId());
int rowsAffected = statement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Updated " + rowsAffected + " row(s)");
}
} catch (Exception e) {
System.out.println("Error updating data: " + e.getMessage());
}
}
// 删除学生
public void delete(int id) {
String sql = "DELETE FROM students WHERE id = ?";
try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement statement = connection.prepareStatement(sql)) {
statement.setInt(1, id);
int rowsAffected = statement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Deleted " + rowsAffected + " row(s)");
}
} catch (Exception e) {
System.out.println("Error deleting data: " + e.getMessage());
}
}
// 查询所有学生
public List<Student> getAll() {
List<Student> students = new ArrayList<>();
String sql = "SELECT * FROM students";
try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS);
Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
Student student = new Student();
student.setId(resultSet.getInt("id"));
student.setName(resultSet.getString("name"));
student.setAge(resultSet.getInt("age"));
students.add(student);
}
} catch (Exception e) {
System.out.println("Error fetching data: " + e.getMessage());
}
return students;
}
}
```
这个类包含了四个静态方法分别对应增删改查操作,注意实际应用中需要处理异常并关闭资源。
阅读全文