时间:2021-07-01 10:21:17 帮助过:6人阅读
//添加纪录
private static void add(){
String id, name, gender;
for (int i = 0; i < 10; i++) {
id = String.valueOf(i);
name = "name" + String.valueOf(i);
gender = i % 2 == 0 ? "male" : "female";
try{
String sql = "INSERT INTO test VALUES(?,?,?);";
Object[] params = {id, name, gender};
queryRunner.update(sql, params);
}catch(SQLException e){
throw new RuntimeException(e);
}
}
}
执行完添加操作后,在MySQL Workbench中查询的结果显示,数据已添加:
编辑信息:
//按照给定ID编辑信息
private static void edit(String id){
try{
String sql = "UPDATE test SET name = ?, gender = ? WHERE id = ?;";
Object[] params = {"change", "female", id};
queryRunner.update(sql,params);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public static void main(String[] args){
edit("0");
}
编辑结果:
删除信息:
//按照给定ID删除信息
private static void delete(String id){
try{
String sql = "DELETE FROM test WHERE id = ?";
queryRunner.update(sql, id);
}catch (SQLException e){
throw new RuntimeException(e);
}
}
public static void main(String[] args){
delete("0");
}
删除结果:
在使用 query 方法时,需要使用 ResultSetHandler, 具体使用方式将在另一篇文章中阐述
将查询的结果,使用 ArrayListHandler,存入ArrayList,以数组形式打印:
private static void showAll(){
try{
String sql = "SELECT * FROM test;";
List<Object[]> list = queryRunner.query(sql, new ArrayListHandler());
for (Object[] aList : list) {
System.out.println(Arrays.toString(aList) + " ");
}
}catch (SQLException e){
throw new RuntimeException(e);
}
}
关于QueryRunner对数据库的CRUD操作就介绍到此了。
抄录文献:
https://www.cnblogs.com/lihanxiang/p/8475548.html
DbUtils入门之QueryRunner
标签:list ams dem logs enc span -o mysq result