当前位置 : 主页 > 编程语言 > c++ >

DBUtils的基本使用

来源:互联网 收集:自由互联 发布时间:2021-07-03
DButils实现增删查改 package com.cn.dbutils;import java.sql.SQLException;import java.util.Date;import org.apache.commons.dbutils.QueryRunner;import org.junit.Test;/* a是数据库的一张表 表结构(id int primary key,name varchar
DButils实现增删查改
package com.cn.dbutils;

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

import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;
/*
    a是数据库的一张表 表结构(id int primary key,name varchar(40),float money)
    source是数据库连接池
**/
//DBUtils的测试
public class TestDBUtils {
	//增
	@Test
	public void add() throws SQLException{
		QueryRunner run = new QueryRunner(DbcpUtils.getSource());
		String sql = "insert into a values(?,?,?)";
		Object[] obj = {23,"lala",1000};
		run.update(sql, obj);
	}
	//删
	@Test
	public void delete() throws SQLException{
		QueryRunner run = new QueryRunner(DbcpUtils.getSource());
		String sql ="delete from a where id=?";
		run.update(sql, 23);
	}
	//改
	@Test
	public void update() throws SQLException{
			QueryRunner run =new QueryRunner(DbcpUtils.getSource());
			String sql = "update a set money=? where id=?";
			Object[] obj = {9999,2};
			run.update(sql, obj);
	}
	//查
	@Test
	public void select() throws SQLException{
		QueryRunner run = new QueryRunner(DbcpUtils.getSource());
		
		//beanHandler 查单个数据,当有多个记录时,查到也是第一个记录
		/*String sql = "select * from a where id=?";
		 * Person p = (Person) run.query(sql, 2, new BeanHandler(Person.class));
		System.out.println(p.getMoney());*/
		
		
		//BeanListHandler查多个数据,封装在bean中
		/*String sql = "select * from a";
		List
 
   list = (List
  
   ) run.query(sql, new BeanListHandler(Person.class));//返回一个list集合 System.out.println(list.size());*/ //ArrayHandler单个记录 /*String sql = "select * from a where id=?"; Object[] obj = (Object[]) run.query(sql, 2, new ArrayHandler()); System.out.println(obj.length);*/ //ColumnListHandler查询某一列的多个数据 /*String sql = "select * from a"; List list = (List) run.query(sql, new ColumnListHandler("name")); System.out.println(list.size());*/ //ScalarHandler将结果封装成一个对象 /*String sql = "select count(*) from a"; Object obj = run.query(sql, new ScalarHandler()); int a = ((Long)obj).intValue(); System.out.println(a);*/ //MapHanddler查询单个数据 /*String sql = "select * from a"; Map map = (Map) run.query(sql, new MapHandler()); System.out.println(map.get("name"));*/ //KeyedHandler /*String sql = "select * from a"; Map 
   
    > map = (Map)run.query(sql, new KeyedHandler("id"));//以id为key for(Map.Entry
    
     > m :map.entrySet()){ int a = m.getKey(); for(Map.Entry
     
       entry:m.getValue().entrySet()){ String name = entry.getKey(); Object value = entry.getValue(); System.out.println(name+" "+value); } }*/ //batch 批处理 String sql = "insert into a values (?,?,?)"; Object[][] obj = new Object[5][3]; for(int i=0;i
     
    
   
  
 
网友评论