给我用QueryRunner写c3p0的增删改查数据
时间: 2024-02-15 15:03:46 浏览: 82
好的,以下是使用QueryRunner和c3p0进行增删改查操作的示例代码:
```java
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0Demo {
private static ComboPooledDataSource dataSource;
static {
dataSource = new ComboPooledDataSource();
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("123456");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
}
public static void main(String[] args) throws SQLException {
QueryRunner queryRunner = new QueryRunner(dataSource);
// 查询
List<User> userList = queryRunner.query("SELECT * FROM user", new BeanListHandler<User>(User.class));
System.out.println(userList);
// 新增
queryRunner.update("INSERT INTO user (name, age) VALUES (?, ?)", "张三", 20);
// 修改
queryRunner.update("UPDATE user SET age = ? WHERE name = ?", 21, "张三");
// 删除
queryRunner.update("DELETE FROM user WHERE name = ?", "张三");
}
public static class User {
private String name;
private int age;
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 "User [name=" + name + ", age=" + age + "]";
}
}
}
```
这里使用了c3p0的ComboPooledDataSource来获取数据库连接,并使用QueryRunner来进行数据库操作。以上代码中的User类仅作为示例,你可以根据自己的需求修改。
阅读全文