DBUtils的使用.

使用步骤

1.导入jar包   

commons-dbutils-xx.jar

c3p0-xxx.jar

mysql-connector-java-xxxx-bin.jar            

2 .创建QueryRunner对象

QueryRunner qr=new QueryRunner(C3p0Utils.getDataSource());

3 .使用query方法执行select语句

package com.wency.dbutils;

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

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

import com.wency.entity.User;


public class TestDBUtils {
	@Test
	public void testFind() throws SQLException{
		
		//创建QuerRunner对象
		QueryRunner qr=new QueryRunner(C3p0Utils.getDataSource());
        List<User> users = qr.query("select * from user",new ResultSetHandler<List<User>>(){

			@Override
			public List<User> handle(ResultSet rs) throws SQLException {
				// TODO Auto-generated method stub
				
				List<User> list=new ArrayList<User>();
				while (rs.next()) {
					User user=new User();
					int id=rs.getInt(1);
					String name=rs.getString(2);
					String pwd=rs.getString(3);
					String email=rs.getString(4);
					user.setId(id);
					user.setPwd(pwd);
					user.setUserName(name);
					user.setEmail(email);
					list.add(user);
				}
				return  list;
			}
			

		});
        
        System.out.println(users);
        
	}
	
	@Test
	public void testSelect2() throws SQLException
	{
		//创建一个QueryRunner对象
		QueryRunner qr=new QueryRunner(C3p0Utils.getDataSource());
		//调用qr的Query()方法
		List<User> list = qr.query("select * from user where _id=?",new BeanListHandler<User>(User.class),2);
	    System.out.println(list);
	}
	
	@Test
	public void testInsert() throws SQLException{
		QueryRunner qr=new QueryRunner(C3p0Utils.getDataSource());
		int update = qr.update("insert into user(userName,pwd,email) values(?,?,?)","小刚","345555","344536@qq.com");
		System.out.println(update);
		
	}
	
	@Test
	public void testUpdate() throws SQLException{
		QueryRunner qr=new QueryRunner(C3p0Utils.getDataSource());
		int update = qr.update("update user set userName=? where _id=?","小美",3);
	}
	
	@Test
	public void testDelete() throws SQLException{
		QueryRunner qr=new QueryRunner(C3p0Utils.getDataSource());
		qr.update("delete from user where _id=?","3");
	}
	
	@Test
	public void testBatch() throws SQLException{
		QueryRunner qr=new QueryRunner(C3p0Utils.getDataSource());
		Object[][] params=new Object[10][];
		for (int i = 0; i < params.length; i++) {
			params[i]=new Object[]{"wency","3344","345@454.com"};
		}
		qr.batch("insert into user(userName,pwd,email) values(?,?,?)", params); 
		
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值