c3p0实线学生增删改
时间: 2023-10-21 15:03:39 浏览: 39
c3p0是一个Java数据库连接池。它本身并不提供增删改的功能,但是在使用c3p0连接数据库后,我们可以使用JDBC来进行增删改操作。下面是一个使用c3p0和JDBC进行学生信息增删改的示例代码:
1. 添加学生信息:
```java
public void addStudent(Student student) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 获取数据库连接
conn = C3p0Utils.getConnection();
// 定义SQL语句,使用?作为占位符
String sql = "INSERT INTO student(name, age, gender) VALUES (?, ?, ?)";
// 创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
// 设置占位符的值
pstmt.setString(1, student.getName());
pstmt.setInt(2, student.getAge());
pstmt.setString(3, student.getGender());
// 执行SQL语句
pstmt.executeUpdate();
} finally {
// 关闭资源
C3p0Utils.close(conn, pstmt, null);
}
}
```
2. 删除学生信息:
```java
public void deleteStudent(int id) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 获取数据库连接
conn = C3p0Utils.getConnection();
// 定义SQL语句,使用?作为占位符
String sql = "DELETE FROM student WHERE id=?";
// 创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
// 设置占位符的值
pstmt.setInt(1, id);
// 执行SQL语句
pstmt.executeUpdate();
} finally {
// 关闭资源
C3p0Utils.close(conn, pstmt, null);
}
}
```
3. 修改学生信息:
```java
public void updateStudent(Student student) throws SQLException {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// 获取数据库连接
conn = C3p0Utils.getConnection();
// 定义SQL语句,使用?作为占位符
String sql = "UPDATE student SET name=?, age=?, gender=? WHERE id=?";
// 创建PreparedStatement对象
pstmt = conn.prepareStatement(sql);
// 设置占位符的值
pstmt.setString(1, student.getName());
pstmt.setInt(2, student.getAge());
pstmt.setString(3, student.getGender());
pstmt.setInt(4, student.getId());
// 执行SQL语句
pstmt.executeUpdate();
} finally {
// 关闭资源
C3p0Utils.close(conn, pstmt, null);
}
}
```
其中,Student类为学生信息类,包含id、name、age、gender等属性和相应的getter和setter方法。C3p0Utils为c3p0连接池的工具类,提供获取数据库连接和关闭资源等方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)