1. 增删改查 常用Handler处理器示例

QueryRunner类提供了两个构造方法:

•默认的构造方法

•需要一个javax.sql.DataSource来作参数的构造方法。

public Object query(Connection conn, String sql, Object[] params, ResultSetHandler rsh) throws SQLException:执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参数。该方法会自行处理PreparedStatement和ResultSet的创建和关闭。

public Object query(String sql, Object[] params, ResultSetHandler rsh) throws SQLException:几乎与第一种方法一样;唯一的不同在于它不将数据库连接提供给方法,并且它是从提供给构造方法的数据源(DataSource)或使用的setDataSource方法中重新获得Connection。

public Object query(Connection conn, String sql, ResultSetHandler rsh) throws SQLException :执行一个不需要置换参数的查询操作。

public int update(Connection conn, String sql, Object[] params) throws SQLException:用来执行一个更新(插入、更新或删除)操作。

public int update(Connection conn, String sql) throws SQLException:用来执行一个不需要置换参数的更新操作。

ResultSetHandler接口的实现类

ArrayHandler:把结果集中的第一行数据转成对象数组。

ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。

BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。

BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。

ColumnListHandler:将结果集中某一列的数据存放到List中。

KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里,再把这些map再存到一个map里,其key为指定的key。

MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。

MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List

public class Demo1 {

/**

create database dbutils;

use dbutils;

create table user(

id int primary key auto_increment,

name varchar(40),

password varchar(40),

email varchar(60),

birthday date

);

insert into user(name,password,email,birthday) values('zs','123','xj@qq.com','1990-06-27');

insert into user(name,password,email,birthday) values('ls','123','xj@qq.com','1990-06-27');

insert into user(name,password,email,birthday) values('ww','123','xj@qq.com','1990-06-27');

* @throws SQLException

*/

@Test

public void add() throws SQLException

{

//创建QueryRunner时带 连接池,获得的连接 用完后会自动归还到连接池

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

String sql = "insert into user(name,password,email,birthday) values(?,?,?,?)";

Object[] params = {"kevin", "12345", "xj@163.com", new Date()};

qr.update(sql, params);

}

@Test

public void delete() throws SQLException

{

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

String sql = "delete from user where id=?";

qr.update(sql, 1);

}

@Test

public void update() throws SQLException

{

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

String sql = "update user set name=? where id=?";

Object[] params = {"xiangjie", 2};

qr.update(sql, params);

}

@Test

public void find() throws SQLException

{

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

String sql = "select * from user where id=?";

Object[] params = {2};

User user = (User) qr.query(sql, new BeanHandler(User.class), params);

System.out.println(user.getName());

}

@Test

public void getAll() throws SQLException

{

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

String sql = "select * from user";

List list = (List) qr.query(sql, new BeanListHandler(User.class));

System.out.println(list.size());

}

@Test

public void testBatch() throws SQLException //SQL批处理

{

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

String sql = "insert into user(name,password,email,birthday) values(?,?,?,?)";

Object[][] params = new Object[10][];

for(int i=0; i<10; i++)

{

params[i] = new Object[]{"xx"+i, "123456", "xj@qq.com", new Date()};

}

qr.batch(sql, params);

}

// dbutils 存储大文本 (不建议使用,无缓存,文本被直接放到内存,很大文本直接用JDBC)

/*

create table testclob

(

id int primary key auto_increment,

resume text

);

*/

@Test

public void testclob() throws IOException, SerialException, SQLException

{

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

String path = Demo1.class.getClassLoader().getResource("test.txt").getPath();

String sql = "insert into testclob(resume) values(?)";

FileReader in =new FileReader(path);

char[] buffer = new char[(int) new File(path).length()];

in.read(buffer);

SerialClob clob = new SerialClob(buffer);

Object[] params = {clob};

qr.update(sql, params);

}

/*

* dbutils 提供的 handler 处理器

*/

@Test

public void testArrayHandler() throws SQLException

{

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

String sql = "select * from user";

Object[] result = (Object[]) qr.query(sql, new ArrayHandler());

System.out.println(Arrays.asList(result));

}

@Test

public void testArrayListHandler() throws SQLException

{

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

String sql = "select * from user";

List list = (List) qr.query(sql, new ArrayListHandler());

for(Object[] obj : list)

System.out.println(Arrays.asList(obj));

}

@Test

public void testKeyedHandler() throws SQLException

{

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

String sql = "select * from user";

Map map = (Map) qr.query(sql, new KeyedHandler("id"));

for(Map.Entry me : map.entrySet())

{

int id = me.getKey();

Map innermap = me.getValue();

for(Map.Entry innerme : innermap.entrySet() )

{

String columnName = innerme.getKey();

Object value = innerme.getValue();

System.out.println(columnName + "=" + value);

}

System.out.println("-----------------");

}

}

@Test

public void testMapHandler() throws SQLException

{

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

String sql = "select * from user";

Map map = (Map) qr.query(sql, new MapHandler());

for(Map.Entry entry : map.entrySet())

{

System.out.println(entry.getKey() + "=" + entry.getValue());

}

}

@Test

public void testMapListHandler() throws SQLException

{

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

String sql = "select * from user";

List> list = (List>) qr.query(sql, new MapListHandler());

for(Map map : list)

{

for(Map.Entry entry : map.entrySet())

{

System.out.println(entry.getKey() + "=" + entry.getValue());

}

System.out.println("------------------");

}

}

@Test

public void testScalarHandler() throws SQLException

{

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

String sql = "select count(*) from user";

long L = (Long) qr.query(sql, new ScalarHandler(1));

int count = (int) L;

System.out.println("count: " + count);

}

}

2. 事务操作

方式一: 能实现功能,但不实用

dao层 提供增删改查,共用一个connect

/*

create table account(

id int primary key auto_increment,

name varchar(40),

money float

);

insert into account(name,money) values('aaa',1000);

insert into account(name,money) values('bbb',1000);

insert into account(name,money) values('ccc',1000);

insert into account(name,money) values('ddd',1000);

*/

public class AccountDao {

private Connection conn = null;

public AccountDao(Connection conn)

{

this.conn = conn;

}

/*

public void transfer() throws SQLException //不实用

{

Connection conn = null;

try {

conn = JdbcUtils_C3P0.getConnection();

conn.setAutoCommit(false);

QueryRunner qr = new QueryRunner();

String sql1 = "update account set money=money-100 where id=1";

String sql2 = "update account set money=money+100 where id=2";

qr.update(conn, sql1);

qr.update(conn, sql2);

conn.commit();

System.out.println("transfer success");

} catch (SQLException e) {

conn.rollback();

e.printStackTrace();

}finally{

conn.close();

}

}

*/

public void update(Account account) throws SQLException

{

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

String sql = "update account set name=?,money=? where id=?";

Object[] params = {account.getName(), account.getMoney(), account.getId()};

qr.update(conn, sql, params);

}

public Account find(int id) throws SQLException

{

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

String sql = "select * from account where id=?";

return (Account) qr.query(conn, sql, id, new BeanHandler(Account.class));

}

}

Service层 提供transfer方法, 操作事务

public class AccountService {

public void transfer(int sourceid, int targetid, float money) throws SQLException

{

Connection conn = null;

try {

conn = JdbcUtils_C3P0.getConnection();

conn.setAutoCommit(false);

AccountDao dao = new AccountDao(conn);

Account source = dao.find(sourceid);

Account target = dao.find(targetid);

source.setMoney(source.getMoney()-money);

target.setMoney(target.getMoney()+money);

dao.update(source);

dao.update(target);

conn.commit();

} catch (SQLException e) {

if(conn!=null)

conn.rollback();

}finally{

if(conn!=null)

conn.close();

}

}

}

方式二: 利用ThreadLocal容器存储Connection, 实用方案

service层

public class AccountService {

public void transfer(int sourceid, int targetid, float money) throws SQLException

{

try {

JdbcUtils_C3P0.startTransaction(); //利用工具类, 开启事务

AccountDao dao = new AccountDao();

Account source = dao.find(sourceid);

Account target = dao.find(targetid);

source.setMoney(source.getMoney()-money);

target.setMoney(target.getMoney()+money);

dao.update(source);

//int i=1/0; //制造异常中断

dao.update(target);

JdbcUtils_C3P0.commit();

} catch (SQLException e) {

e.printStackTrace();

JdbcUtils_C3P0.rollback(); //回滚

}finally{

JdbcUtils_C3P0.release(); //释放连接

}

}

}

Dao层

public class AccountDao {

private Connection conn = null;

public AccountDao(Connection conn)

{

this.conn = conn;

}

public AccountDao(){}

public void update(Account account) throws SQLException

{

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

String sql = "update account set name=?,money=? where id=?";

Object[] params = {account.getName(), account.getMoney(), account.getId()};

qr.update(JdbcUtils_C3P0.getConnection(), sql, params); //利用工具类获得连接

}

public Account find(int id) throws SQLException

{

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

String sql = "select * from account where id=?";

return (Account) qr.query(JdbcUtils_C3P0.getConnection(), sql, id, new BeanHandler(Account.class));

}

}

工具类:

public class JdbcUtils_C3P0 {

private static ComboPooledDataSource ds = null;

private static ThreadLocal threadLocal = new ThreadLocal(); //Threadlocal容器

static{

ds = new ComboPooledDataSource("c3p0config");

}

public static Connection getConnection() throws SQLException{

Connection conn = threadLocal.get();

if(conn==null)

{

conn = getDataSource().getConnection();

threadLocal.set(conn);

}

return conn;

}

public static DataSource getDataSource()

{

return ds;

}

public static void startTransaction()

{

Connection conn = threadLocal.get();

try{

if(conn == null)

{

conn = getDataSource().getConnection();

threadLocal.set(conn);

}

conn.setAutoCommit(false);

}

catch(Exception e)

{

throw new RuntimeException(e);

}

}

public static void rollback()

{

try

{

Connection conn = threadLocal.get();

if(conn!=null)

conn.rollback();

}

catch (Exception e)

{

throw new RuntimeException(e);

}

}

public static void commit()

{

try

{

Connection conn = threadLocal.get();

if(conn!=null)

conn.commit();

}

catch (Exception e)

{

throw new RuntimeException(e);

}

}

public static void release()

{

try

{

Connection conn = threadLocal.get();

if(conn!=null)

{

conn.close();

threadLocal.remove();

}

}

catch (Exception e)

{

throw new RuntimeException(e);

}

}

}

工具类C3P0配置文档

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/transaction

root

123456

5

10

5

100

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/dbutils

root

123456

5

10

5

100

mysql java dbutil_Java -- DBUtils 框架 操作MySQL数据库相关推荐

  1. Python FastAPI 框架 操作Mysql数据库 增删改查

    2 比 1 更容易理解,可以先看2(单文件级别) 1.FastAPI 框架 操作Mysql数据库(项目多文件级别) FastAPI 可以使用任何您想要的关系型数据库. 在这里,让我们看一个使用着SQL ...

  2. .NET 使用 MySql.Data.dll 动态库操作MySql的帮助类--MySqlHelper

    .NET 使用 MySql.Data.dll 动态库操作MySql的帮助类--MySqlHelper 參考演示样例代码,例如以下所看到的: /// <summary>/// MySql 数 ...

  3. oracle19c方言,JFinal框架操作oracle数据库

    JFinal框架操作oracle数据库,需要在configPlugin()方法中配置链接oracle数据库的相关配置 配置JFinal数据库操作插件,configPlugin方法 这里我加载jdbc. ...

  4. jfinal连接oracle_JFinal框架操作oracle数据库

    JFinal框架操作oracle数据库,需要在configPlugin()方法中配置链接oracle数据库的相关配置 配置JFinal数据库操作插件,configPlugin方法 这里我加载jdbc. ...

  5. 基于Java(SSH 框架)+MySQL 实现的物流配送管理系统【100010488】

    基于 Java 中 SSH 框架的物流配送管理系统 项目各文件介绍 Logistics_Manage_System 项目主文件,也就是该项目你需要导入运行的文件 hibernate_mapping 这 ...

  6. perl mysql 数据推拉_Perl操作Mysql数据库

    1. CGI变量简介 如果你在以前使用过传统的CGI,你应该对"CGI变量"的概念很熟悉. 由这些变量可以取得一些和请求(Request)有关的信息.其中一些来自于 HTTP 请求 ...

  7. sqlite mysql php_PHP实现的简单操作SQLite数据库类与用法示例

    本文实例讲述了PHP实现的简单操作SQLite数据库类与用法.分享给大家供大家参考,具体如下: SQLite是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已 ...

  8. c语言mysql自动重连接_c++操作mysql数据库

    就拿查询MySQL获取结果集并在页面上显示数据为例来分析. HTTP请求由C级别的程序比如Apache/Nginx处理(Java的HTTP服务用的是Java开发的Tomcat等), PHP则调用内置在 ...

  9. adodb mysql.inc.php,php adodb操作mysql数据库示例(增删改查)

    php adodb操作mysql数据库示例(增删改查) 发布于 2014-10-05 08:16:18 | 113 次阅读 | 评论: 0 | 来源: 网友投递 PHP开源脚本语言PHP(外文名: H ...

最新文章

  1. DNS隧道之DNS2TCP使用心得教程——是可以用来穿透qiang的,ubuntu下直接apt install dns2tcp...
  2. http 301 和 302的区别
  3. itchat爬取朋友圈签名制作词云
  4. mysql---批量插入数据:100w条数据
  5. 用html编写输出今天是星期几,利用Date对象编写程序,判断并输出今天是开学的第几周,星期几。...
  6. 关键字restrict简介
  7. jquery 序列化表格内容为字符串(serialize)
  8. android if else语句,Android一起执行IF和ELSE语句
  9. Spring Cloud学习笔记-009
  10. ActiveX控件安装和IE安全设置之间的关系
  11. 新手学Docker(1)Hello World
  12. python numpy库下载_Numpy库的下载与安装总结
  13. HTML5+CSS大作业——宝马轿车网页设计(6页) web前端设计与开发期末作品/期末大作业
  14. 算法——最好理解的动态规划之01背包详解(看完这篇再不敢说自己不知道01背包算法!!!)
  15. oracle 按照中文姓首字母排序,按照偏旁部首,笔画排序 sql
  16. 修改DarkNet的weights文件以编辑模型版本号
  17. 关于阶乘的计算出现负数,数据溢出的问题
  18. hexo图片展示-blog图床迁移至七牛云
  19. 若微型计算机在工作时突然断电,北语网院20春《计算机基础》作业_1234
  20. oracle 10g xe 12505,ORACLE10g的ORA-12505问题解决方法

热门文章

  1. 如何重装win8系统,win8系统重装的方法
  2. 系统对接方案_一个呼叫中心系统组建的案例
  3. python画彩色螺旋线_Python turtle 绘制彩色螺旋线
  4. stm32捕获占空比_「话说定时器系列」之六:STM32定时器输入捕获话题
  5. ❤️《微服务开发—Swagger》(建议收藏)
  6. 字体系统之字体粗细(CSS、HTML)
  7. 实验2-4-2 生成3的乘方表 (C语言)
  8. 模型相关:SolidWorks创建Cube模型,在3DMax中给不同面添加不同颜色,导出自带纹理的FBX至Unity
  9. C# .NET与数据结构
  10. ES6学习之 -- Set数据结构