当前位置:Gxlcms > 数据库问题 > 数据库实用小工具之-DBUtils简单入门

数据库实用小工具之-DBUtils简单入门

时间:2021-07-01 10:21:17 帮助过:9人阅读

1 DBUtils简介
DBUtils是Apache Commons组件中的一员,开源免费!
DBUtils是对JDBC的简单封装,但是它还是被很多公司使用!
DBUtils的Jar包:dbutils.jar

2 DBUtils主要类
?	DbUtils:都是静态方法,一系列的close()方法;
?	QueryRunner:
?	update():执行insert、update、delete;
?	query():执行select语句;
?	batch():执行批处理。

OK,我们卡死写一个例子,这里例子中,我们用c3p0作为数据库连接池,简单实用。


老规矩新建一个项目:

技术分享


我把代码给附上:从上往下的顺序

package com;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;

public class Domain {
	
	/**
	 * 测试添加
	 * @throws SQLException
	 */
	@Test
	public void testadd() throws SQLException
	{
		Person person = new Person();
		person.setId(6);
		person.setName("ddlk");
		person.setMoney(10000);
		this.add(person);
	}
	/**
	 * 测试更新
	 * @throws SQLException
	 */
	@Test
	public void testupdata() throws SQLException
	{
		Person person = new Person();
		person.setId(6);
		person.setName("ddddd");
		person.setMoney(100000);
		this.update(person);
	}
	
	/**
	 * 测试查询
	 * @throws SQLException
	 */
	@Test
	public void testquery() throws SQLException
	{
		Person person = new Person();
		person.setId(6);
		person.setName("ddddd");
		person.setMoney(100000);
		this.update(person);
	}
	
	/**
	 * 测试删除
	 * @throws SQLException
	 */
	@Test
	public void testdelete() throws SQLException
	{ 
		//删除id为5的用户
		this.delete("5");
	}
	
	public void add(Person person) throws SQLException
	{
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "insert into person values(?,?,?);";
		qr.update(sql, person.getId(),person.getName(),person.getMoney());
	}
	
	public void update(Person person) throws SQLException
	{
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "update  person set name=? , money=? where id=?";
		qr.update(sql, person.getName(),person.getMoney(),person.getId());
	}
	
	public void delete(String person_id) throws SQLException
	{
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "delete from  person  where id=?";
		qr.update(sql,person_id);
	}
	
	
	//下面都是Query,查询是比较繁琐的,6种查询模式
	/**查询方法1:
	 * BeanHandler:单行结果集处理器,把数据封装到一个javaBean中
	 * @throws SQLException
	 */
	@Test
	public void query_1() throws SQLException
	{
		 
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from  person where id=?";
		
		/**
		 * ResultSetHandler接口只有一个方法:T handle(ResultSet)
		 * BeanHandler实现了这个接口,它会把结果集数据封装到Student对象中
		 */
		ResultSetHandler<Person> rsh = new BeanHandler<Person>(Person.class);
		Person person = qr.query(sql, rsh, "2");
		System.out.println(person.getName());
		 
	}
	
	/**
	 * 查询方法2:
	 *  BeanListHandler --> 多行结果集处理器,把多行的数据封装到多个Bean对象中,返回一个List<Bean>
	 * @throws SQLException
	 * @throws SQLException 
	 */
	@Test
	public void query_2() throws SQLException
	{
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from person ";
		
		ResultSetHandler<List<Person>> rsh = new BeanListHandler<Person>(Person.class);
		List<Person> personlist = qr.query(sql, rsh);
		
		for(int i=0;i<personlist.size();i++)
		{
			//这返回的都是对象的list
			System.out.println(personlist.get(i));
		}
		
	}
	
	/**方法3
	 * MapHandler --> 单行处理器,把一行结果集封装到一个Map对象中
	 * 
	 * 返回的map中key是列名称,值是列的值
	 * 
	 */
	@Test
	public void query_3() throws SQLException
	{
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from person where id=?";
		//mapHandler 单行处理,封装成一个map
		MapHandler map = new MapHandler();
		
		Map<String,Object> maps = qr.query(sql, map,"3");
		System.out.println(maps);
		
	}
	
	/**方法4
	 * MapListHandler -->多行处理器,把每行结果集封装到一个Map中,多行就是多个Map,即List<Map>
	 * 
	 * 返回的map中key是列名称,值是列的值
	 * 
	 */
	@Test
	public void query_4() throws SQLException
	{
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from person ";
		//mapHandler 单行处理,封装成一个map
		MapListHandler map = new MapListHandler();
		
		List<Map<String,Object>> maps = qr.query(sql, map);
		//增强for循环
		for(Map<String,Object> map1: maps)
		{
			System.out.println(map1);
		}
			
	
	}
	
	/**方法5
	 * ColumnListHandler --> 一列多(单)行,用来处理单列查询,把该列的数据封装到一个List中
	 * @throws SQLException
	 * 
	 */
	@Test
	public void query_5() throws SQLException
	{
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select name from person ";//如果是select * 那查询的是第一列
		ColumnListHandler columnListHandler = new ColumnListHandler();
		
		List<Object> personlist = qr.query(sql, columnListHandler);
		
		for(int i = 0;i<personlist.size();i++)
		{
			System.out.println(personlist.get(i));
		}
		
	}
	
	/**方法6
	 * ScalarHandler --> 通过用在聚合函数的使用,对单行单列进行查询
	 * @throws SQLException
	 */
	@Test
	public void query_6() throws SQLException {
		QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select count(*) from person";
		ScalarHandler shd = new ScalarHandler();
		Number number = (Number)qr.query(sql, shd);
		System.out.println(number.longValue());
	}
	
	
	
}


package com;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
 * Jdbc工具
 * 提供连接池
 * 提供链接
 * @author 挨踢界小人物
 *
 */
public class JdbcUtils {
	public static DataSource ds = new ComboPooledDataSource("myc3p0");
	
	public static Connection getConnection() throws SQLException
	{
		return ds.getConnection();
	}
	
	public static DataSource getDataSource()
	{
		return ds;
	}
}


package com;

public class Person {
	private int id;
	private String name;
	private int money;
	
	public Person() {
		// TODO Auto-generated constructor stub
	}

	
	public Person(int id, String name, int money) {
		super();
		this.id = id;
		this.name = name;
		this.money = money;
	}


	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getMoney() {
		return money;
	}

	public void setMoney(int money) {
		this.money = money;
	}
	
	
}

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

    <named-config name="myc3p0">
        
        <!-- 指定连接数据源的基本属性:!这里的用户名密码要改成自己数据库的用户名密码!~ -->
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
        
        <!-- 若数据库中连接数不足时, 一次向数据库服务器申请多少个连接 -->
        <property name="acquireIncrement">5</property>
        <!-- 初始化数据库连接池时连接的数量 -->
        <property name="initialPoolSize">5</property>
        <!-- 数据库连接池中的最小的数据库连接数 -->
        <property name="minPoolSize">5</property>
        <!-- 数据库连接池中的最大的数据库连接数 -->
        <property name="maxPoolSize">10</property>

        <!-- C3P0 数据库连接池可以维护的 Statement 的个数 -->
        <property name="maxStatements">20</property>
        <!-- 每个连接同时可以使用的 Statement 对象的个数 -->
        <property name="maxStatementsPerConnection">5</property>
    
    </named-config>
        
</c3p0-config>
 


数据库脚本文件也给上吧:

/*
SQLyog Ultimate v11.24 (32 bit)
MySQL - 5.5.24 : Database - test
*********************************************************************
*/


/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=''*/;

/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET latin1 */;

USE `test`;

/*Table structure for table `person` */

DROP TABLE IF EXISTS `person`;

CREATE TABLE `person` (
  `id` int(12) NOT NULL,
  `name` varchar(20) DEFAULT NULL,
  `money` int(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `person` */

insert  into `person`(`id`,`name`,`money`) values (1,'zhang1',1001),(2,'zhang2',1002),(3,'zhang3',1003),(4,'zhang4',1004),(5,'tttttt',60000),(6,'aaass',12345);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;



导入所需要的jar文件:点击下载

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jdbcutils_demo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

每一个都可以在方法里面用右键然后选择:JunitTest

技术分享


就可以在控制台看到打印的信息了。是不是很好用,很喜欢!~快来试一试吧!转载请注明出处。

版权声明:本文为博主原创文章,未经博主允许不得转载。

数据库实用小工具之-DBUtils简单入门

标签:jdbcutils

人气教程排行