jdbc增删改查封装方法
时间: 2023-09-03 13:15:36 浏览: 49
以下是Java JDBC的增删改查封装方法的示例:
1. 连接数据库
```java
public Connection getConnection() throws SQLException {
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "password";
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
```
2. 查询数据
```java
public List<Student> findAll() throws SQLException {
List<Student> students = new ArrayList<>();
String sql = "SELECT * FROM student";
Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Student student = new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
student.setGender(rs.getString("gender"));
student.setDepartment(rs.getString("department"));
students.add(student);
}
return students;
}
```
3. 插入数据
```java
public int insert(Student student) throws SQLException {
String sql = "INSERT INTO student(name, age, gender, department) VALUES (?, ?, ?, ?)";
Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setInt(2, student.getAge());
pstmt.setString(3, student.getGender());
pstmt.setString(4, student.getDepartment());
int result = pstmt.executeUpdate();
return result;
}
```
4. 更新数据
```java
public int update(Student student) throws SQLException {
String sql = "UPDATE student SET name=?, age=?, gender=?, department=? WHERE id=?";
Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, student.getName());
pstmt.setInt(2, student.getAge());
pstmt.setString(3, student.getGender());
pstmt.setString(4, student.getDepartment());
pstmt.setInt(5, student.getId());
int result = pstmt.executeUpdate();
return result;
}
```
5. 删除数据
```java
public int delete(int id) throws SQLException {
String sql = "DELETE FROM student WHERE id=?";
Connection conn = getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
int result = pstmt.executeUpdate();
return result;
}
```