第十七天dbutils的使用------CommonsDbUtils(Apache)第三方的:只
所实现的功能差不多。这是第三方开发的,要导入相应的jar包(就一个jar包),比自己写的强大。强大之处在于结果集的处理。主要涉及的类是 org.apache.commons.dbutils Class QueryRunner API如下: Constructor Summary QueryRunner () Constructor for QueryR
所实现的功能差不多。这是第三方开发的,要导入相应的jar包(就一个jar包),比自己写的强大。强大之处在于结果集的处理。主要涉及的类是
org.apache.commons.dbutils
Class QueryRunner
API如下:
Constructor Summary | |
---|---|
QueryRunner() Constructor for QueryRunner. |
|
QueryRunner(boolean pmdKnownBroken) Constructor for QueryRunner, allows workaround for Oracle drivers |
|
QueryRunner(DataSource ds) Constructor for QueryRunner which takes a DataSource. |
|
QueryRunner(DataSource ds, boolean pmdKnownBroken) Constructor for QueryRunner, allows workaround for Oracle drivers. |
Method Summary | ||
---|---|---|
int[] |
batch(Connection conn, String sql, Object[][] params) Execute a batch of SQL INSERT, UPDATE, or DELETE queries. |
|
int[] |
batch(String sql, Object[][] params) Execute a batch of SQL INSERT, UPDATE, or DELETE queries. |
|
|
query(Connection conn, String sql, Object[] params, ResultSetHandler Deprecated. Use query(Connection,String,ResultSetHandler,Object...) instead |
|
|
query(Connection conn, String sql, Object param, ResultSetHandler Deprecated. Use query(Connection, String, ResultSetHandler, Object...) |
|
|
query(Connection conn, String sql, ResultSetHandler Execute an SQL SELECT query without any replacement parameters. |
|
|
query(Connection conn, String sql, ResultSetHandler Execute an SQL SELECT query with replacement parameters. |
|
|
query(String sql, Object[] params, ResultSetHandler Deprecated. Use query(String, ResultSetHandler, Object...) |
|
|
query(String sql, Object param, ResultSetHandler Deprecated. Use query(String, ResultSetHandler, Object...) |
|
|
query(String sql, ResultSetHandler Executes the given SELECT SQL without any replacement parameters. |
|
|
query(String sql, ResultSetHandler Executes the given SELECT SQL query and returns a result object. |
|
int |
update(Connection conn, String sql) Execute an SQL INSERT, UPDATE, or DELETE query without replacement parameters. |
|
int |
update(Connection conn, String sql, Object... params) Execute an SQL INSERT, UPDATE, or DELETE query. |
|
int |
update(Connection conn, String sql, Object param) Execute an SQL INSERT, UPDATE, or DELETE query with a single replacement parameter. |
|
int |
update(String sql) Executes the given INSERT, UPDATE, or DELETE SQL statement without any replacement parameters. |
|
int |
update(String sql, Object... params) Executes the given INSERT, UPDATE, or DELETE SQL statement. |
|
int |
update(String sql, Object param) Executes the given INSERT, UPDATE, or DELETE SQL statement with a single replacement parameter. |
一、框架编写准备:数据库元数据的获取
1、元数据:数据库、表、列的定义信息
二、编写自己的框架简化JDBC开发
CUD:语句不同和参数不同。
三、ORM:
O:Object
R:Relation
M:Mapping
对象关系映射
JavaBean 关系数据库表结构 :对应的映射关系
Hibernate:ORM映射框架 -----》规范化:JPA(Java Persistent API)
IBatis(Apache):ORM映射框架----------->2010(google) MyBatis
Commons DbUtils(Apache):只是对JDBC编码进行了简单的封装。
Spring JDBC Template:只是对JDBC编码进行了简单的封装。
例子:不用自己关闭资源,底层源代码已经关了,而且是结合dbcp使用的,关闭不是真的关闭,而是加入到连接池中,以后就放心使用,一句话解决crud操作。
//账户维护 public class DBUtilDemo { private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource()); @Test public void testAdd() throws Exception{ qr.update("insert into account(name,money) values(?,?)", "fff",1000); } @Test public void testFindOne() throws Exception{ Account a = qr.query("select * from account where id=?", new BeanHandler<Account>(Account.class),1); System.out.println(a); } @Test public void testFindAll() throws Exception{ List<Account> list = qr.query("select * from account", new BeanListHandler<Account>(Account.class)); for(Account a:list) System.out.println(a); } //插入大文本行不行:知道clob对应的类型是什么 /* * create table t1(id int,content text); */ @Test public void testText() throws Exception{ File file = new File("src/jpm.txt"); Reader reader = new FileReader(file);//流并没有对应的数据库类型 char ch[] = new char[(int)file.length()]; reader.read(ch);//不好,开发中不用 reader.close(); Clob clob = new SerialClob(ch); qr.update("insert into t1(id,content) values(?,?)", 1,clob); } //插入大二进制行不行:知道blob对应的类型是什么 /* * create table t2(id int,content longblob); */ @Test public void testBlob() throws Exception{ InputStream in = new FileInputStream("src/1.jpg"); byte b[] = new byte[in.available()]; in.read(b); in.close(); Blob blob = new SerialBlob(b); qr.update("insert into t2(id,content) values(?,?)", 1,blob); } //批处理 /* * create table t3(id int,name varchar(200)); */ @Test public void testBatch()throws Exception{ Object params[][] = new Object[10][];//第1维,插入的条数。第2维,每条需要的参数 for(int i=0;i<params.length;i++){ params[i] = new Object[]{i+1,"aaa"+(i+1)}; } qr.batch("insert into t3 values(?,?)", params); } }
部分源代码如下:说明已经关闭资源了。
public int update(String sql, Object... params) throws SQLException { Connection conn = this.prepareConnection(); return this.update(conn, true, sql, params); } /** * Calls update after checking the parameters to ensure nothing is null. * @param conn The connection to use for the update call. * @param closeConn True if the connection should be closed, false otherwise. * @param sql The SQL statement to execute. * @param params An array of update replacement parameters. Each row in * this array is one set of update replacement values. * @return The number of rows updated. * @throws SQLException If there are database or parameter errors. */ private int update(Connection conn, boolean closeConn, String sql, Object... params) throws SQLException { if (conn == null) { throw new SQLException("Null connection"); } if (sql == null) { if (closeConn) { close(conn); } throw new SQLException("Null SQL statement"); } PreparedStatement stmt = null; int rows = 0; try { stmt = this.prepareStatement(conn, sql); this.fillStatement(stmt, params); rows = stmt.executeUpdate(); } catch (SQLException e) { this.rethrow(e, sql, params); } finally { close(stmt); if (closeConn) { close(conn); } } return rows; } }
DBUtils框架提供的结果处理器例子:
public class ResultSetHandlerDemo { private QueryRunner qr = new QueryRunner(DBCPUtil.getDataSource()); //ArrayHandler:把结果集中的第一行数据转成对象数组。 @Test public void test1() throws SQLException{ //数组中的元素就是记录的每列的值 Object[] objs = qr.query("select * from account where id=?", new ArrayHandler(), 1); for(Object obj:objs) System.out.println(obj); } //ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。 @Test public void test2() throws SQLException{ //数组中的元素就是记录的每列的值 List<Object[]> list = qr.query("select * from account", new ArrayListHandler()); for(Object[] objs:list){ System.out.println("------------------"); for(Object obj:objs){ System.out.println(obj); } } } //ColumnListHandler:将结果集中某一列的数据存放到List中。 投影 @Test public void test3() throws SQLException{ //数组中的元素就是记录的每列的值 List<Object> list = qr.query("select * from account", new ColumnListHandler("name")); for(Object objs:list){ System.out.println(objs); } } //KeyedHandler(name):将结果集中的每一行数据都封装到一个Map<列名,列值>里,再把这些map再存到一个map里,其key为指定的key。 @Test public void test4() throws SQLException{ Map<Object,Map<String,Object>> bmap= qr.query("select * from account", new KeyedHandler("id")); for(Map.Entry<Object,Map<String,Object>> bme:bmap.entrySet()){ System.out.println("-----------------"); for(Map.Entry<String,Object> lme:bme.getValue().entrySet()){ System.out.println(lme.getKey()+"="+lme.getValue()); } } } //MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值 @Test public void test5() throws SQLException{ Map<String,Object> map = qr.query("select * from account where id=?", new MapHandler(),1); for(Map.Entry<String,Object> lme:map.entrySet()){ System.out.println(lme.getKey()+"="+lme.getValue()); } } //MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List @Test public void test6() throws SQLException{ List<Map<String,Object>> list= qr.query("select * from account", new MapListHandler()); for(Map<String,Object> map:list){ System.out.println("-----------------"); for(Map.Entry<String,Object> lme:map.entrySet()){ System.out.println(lme.getKey()+"="+lme.getValue()); } } } //ScalarHandler :只有一条记录的投影查询 select count(*) from account; @Test public void test7() throws SQLException{ // Object obj = qr.query("select * from account where id=?", new ScalarHandler("name"),1); // System.out.println(obj); Object obj = qr.query("select count(*) from account", new ScalarHandler(1)); int num = ((Long)obj).intValue(); System.out.println(num); } }

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Get started easily: How to use pip mirror source With the popularity of Python around the world, pip has become a standard tool for Python package management. However, a common problem that many developers face when using pip to install packages is slowness. This is because by default, pip downloads packages from Python official sources or other external sources, and these sources may be located on overseas servers, resulting in slow download speeds. In order to improve download speed, we can use pip mirror source. What is a pip mirror source? To put it simply, just
