码迷,mamicode.com
首页 > 数据库 > 详细

黑马day12 DbUtils的介绍

时间:2015-07-02 17:39:34      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:dbutils

简介:

DbUtils为不喜欢hibernate框架的钟爱,它是线程安全的,不存在并发问题。

使用步骤:

1. QueryRunner runner=new QueryRunner(这里写数据源...如c3p0的数据元new ComboPooledDataSource()或者dbcp的数据元);

2.使用runner的方法如果要增删改就使用update(String sql,Object ... params) 

sql:传递的sql语句

params:可变参数,为sql语句中的?所代替的参数

 使用runner的方法要查询使用runner的query(String sql,ResultSetHandle handle ,Object ... params)

sql:传递的sql语句

handle :一个接口要是实现其中的handle方法

params:可变参数,为sql语句中的?所代替的参数

案例:

package com.itheima.dbutils;

import java.sql.ResultSet;
import java.sql.SQLException;

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

import com.itheima.domain.Account;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DbUtilsDemo1 {
	@Test
	public void add() throws SQLException{
		QueryRunner runner=new QueryRunner(new ComboPooledDataSource());
		runner.update("insert into account values(null,?,?)", "韩玮",7000);
	}
	@Test
	public void update() throws SQLException{
		QueryRunner runner=new QueryRunner(new ComboPooledDataSource());
		runner.update("update account set money=? where name=?", 9000,"李卫康");
	}
	@Test
	public void delete() throws SQLException{
		QueryRunner runner=new QueryRunner(new ComboPooledDataSource());
		runner.update("delete from account where name=?","韩玮");
	}
	@Test
	public void query() throws SQLException{
		final Account account=new Account();
		QueryRunner runner=new QueryRunner(new ComboPooledDataSource());
		runner.query("select * from account where name =?", new ResultSetHandler<Account>(){
			@Override
			public Account handle(ResultSet rs) throws SQLException {
				while(rs.next()){
					account.setId(rs.getInt("id"));
					account.setName(rs.getString("name"));
					account.setMoney(rs.getDouble("money"));
				}
				return account;
			}
			
		}, "李卫康");
		System.out.println(account.getMoney());
	}
}
运行结果查询数据库:

mysql> select * from account;
+----+--------+-------+
| id | name   | money |
+----+--------+-------+
|  1 | 李卫康 |  9000 |
+----+--------+-------+
1 row in set


mysql> select * from account;
+----+--------+-------+
| id | name   | money |
+----+--------+-------+
|  1 | 李卫康 | 10000 |
+----+--------+-------+
1 row in set


mysql> select * from account;
+----+--------+-------+
| id | name   | money |
+----+--------+-------+
|  1 | 李卫康 | 10000 |
|  5 | 程崇树 |  5000 |
+----+--------+-------+

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

黑马day12 DbUtils的介绍

标签:dbutils

原文地址:http://blog.csdn.net/u014010769/article/details/46727395

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!