JavaWeb学习-DBUtils框架-2-DBUtils的CRUD操作练习

这篇来继续练习下DBUtils这个工具类和三个核心对象的使用,来一个CURD练习。

1.查询

前面我们查询了全部users对象,这个例子,我们通过其中一个支持多个参数的构造函数来查询待条件的用户。

package com.anthony.test;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import com.anthony.datasource.C3P0Utils;
import com.anthony.entity.User;

public class TestJDBC {

	@Test
	public void test2() throws SQLException {
		
		QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
		//利用其中一个支持多参数的构造方法
		List<User> list = qr.query("select * from users where id=?", new BeanListHandler<User>(User.class),2);
		//遍历user集合
		for(User u : list) {
			System.out.println(u);
		}
	}

}

上面query()这个构造方法,是支持多个参数的,有几个?,你就后面用逗号隔开,写几个参数。上面就是一个参数的例子,查询用户id=1的举例。

运行结果

User [username=Anthony, password=123456, email=anthony@163.com, birthday=2018-08-08, id=2]

2.插入

正常插入sql语句是这么写的,id字段是自动增长的。

insert into users(username,password,email,birthday) values ('ZS','1234','ZS@163.com','2008-09-10');
package com.anthony.test;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import com.anthony.datasource.C3P0Utils;
import com.anthony.entity.User;

public class TestJDBC {

	@Test
	public void test2() throws SQLException {
		
		QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
		//利用其中一个支持多参数的构造方法
		qr.update("insert into users(username,password,email,birthday) values (?,?,?,?);", "ZS","1234","zs@1163.com", "2008-10-19");
		
	}

}

自己用小海豚sqlyog工具去检查下是否发现新数据插入。

3.更新

例如上面插入zs对于id是5,我想把这个改成3

package com.anthony.test;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import com.anthony.datasource.C3P0Utils;

public class TestJDBC {

	@Test
	public void test2() throws SQLException {
		
		QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
		//利用其中一个支持多参数的构造方法
		qr.update("update users set id=? where username=?", "3","ZS");
		
	}

}

 

4.删除

这里把ZS给删除

package com.anthony.test;

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import com.anthony.datasource.C3P0Utils;

public class TestJDBC {

	@Test
	public void test2() throws SQLException {
		
		QueryRunner qr = new QueryRunner(C3P0Utils.getDataSource());
		//利用其中一个支持多参数的构造方法
		qr.update("delete from users where username=?","ZS");
		
	}

}

使用DBUtils这个框架,只需要关心写sql语句就好了,其他代码基本上就两行搞定。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值