search
HomeDatabaseMysql TutorialDbUtils操作数据库

DbUtils操作数据库

Jun 07, 2016 pm 04:02 PM
dbutilsWhatoperatedatabase

1.什么是O-R Mapping(对象-关系映射) 常用O-R Mapping映射工具 Hibernate(全自动框架) Ibatis(半自动框架/SQL) Commons DbUti ls(只是对JDBC简单封装) 还有JPA等之类的,这个不是特别了解,到目前为止也就接触了Hibernate和DbUtils,Hiabernate给人的不用

1.什么是O-R Mapping(对象-关系映射)

常用O-R Mapping映射工具

Hibernate(全自动框架)

Ibatis(半自动框架/SQL)

Commons DbUti ls(只是对JDBC简单封装)

还有JPA等之类的,这个不是特别了解,到目前为止也就接触了Hibernate和DbUtils,Hiabernate给人的不用写SQl语句,直接用配置文件去映射关系,DuUtils仍然要写sql语句,他只不过简化了crud的操作(个人看法)

2.dbutils的介绍

commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。DBUtils框架最核心的类,就是QueryRunner类还一个重要的接口ResultSetHandler(接口).

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

1>默认的构造方法

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

3>public Object query(Connection conn, String sql, Object[] params, ResultSetHandler rsh) throws

SQLException:执行一个查询操作,在这个查询中,对象数组中的每个元素值被用来作为查询语句的置换参

数。该方法会自行处理 PreparedStatement 和 ResultSet 的创建和关闭。

4>public Object query(String sql, Object[] params, ResultSetHandler rsh) throws SQLException: 几乎

与第一种方法一样;唯一的不同在于它不将数据库连接提供给方法,并且它是从提供给构造方法的数据源

(DataSource) 或使用的setDataSource 方法中重新获得 Connection。
5>public Object query(Connection conn, String sql, ResultSetHandler rsh) throws SQLException : 执行一个不需要置换参数的查询操作。
6>public int update(Connection conn, String sql, Object[] params) throws SQLException:用来执行一个更新(插入、更新或删除)操作。
7>public int update(Connection conn, String sql) throws SQLException:用来执行一个不需要置换参数的更新操作。

4.ResultSetHandler接口

1>该接口用于处理 java.sql.ResultSet,将数据按要求转换为另一种形式。

2>ResultSetHandler 接口提供了一个单独的方法:Object handle (java.sql.ResultSet .rs)。

3>ResultSetHandler 接口的实现类

a>BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。(这个是针对javabean)

b>BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。(这个是针对javabean)

c>ArrayHandler:把结果集中的第一行数据转成对象数组。(这个是针对数组的)

d>ArrayListHandler:把结果集中的每一行数据都转成一个对象数组,再存放到List中。(这个是针对数组的)

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

f>MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List。(这个是针对Map)

h>ScalarHandler:结果集中只有一行一列数据。(这个是针对Long)

5.DbUtils类

DbUtils :提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。主要方法如下:

1>public static void close(…) throws java.sql.SQLException: DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭Connection、Statement和ResultSet。

2>public static void closeQuietly(…): 这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLException。
3>public static void commitAndCloseQuietly(Connection conn): 用来提交连接,然后关闭连接,并且在关闭连接时不抛出SQL异常。

4>public static boolean loadDriver(java.lang.String driverClassName):这一方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,你不需要捕捉这个异常ClassNotFoundException。

6.注意:
1>DBUtils对象的update()方法,内部已经关闭相关的连接对象

2>update(Connection)方法带有Connection对象的,需要手工关闭,其它对象自动关闭

update()方法无Connection对象的,DBUtils框架自动关闭

3>以上这样做的额原因是:主要考虑了在分层结构中,需要用到同一个Connection的问题

7.代码练习

package cn.wwh.www.web.jdbc.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
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;

import cn.wwh.www.web.jdbc.domain.User;
import cn.wwh.www.web.jdbc.util.JdbcUtils;

/**
 *类的作用: ResultSetHandler接口的各种实现类的简单用法
 * 
 *@author 一叶扁舟
 *@version 1.0
 *@创建时间: 2014-9-6 下午04:16:43
 */

public class Demo4 {

	@Test
	public void testBeanHandler() throws SQLException {
		QueryRunner run = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from UserInfo";
		User user = run.query(sql, new BeanHandler(User.class));
		System.out.println("beanHandler" + user.toString());

	}

	@Test
	public void testBeanListHandler() throws SQLException {
		QueryRunner run = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from UserInfo";
		List<User> users = run.query(sql, new BeanListHandler(User.class));
		for (User user : users) {
			System.out.println(user.toString());
			System.out.println();

		}

	}

	@Test
	public void testArrayHandler() throws SQLException {
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from userInfo";
		Object[] array = (Object[]) runner.query(sql, new ArrayHandler());
		System.out.println("编号 : " + array[0]);
		System.out.println("用户名 : " + array[1]);
	}

	@Test
	public void testArrayListHandler() throws SQLException {
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from userInfo";
		List<Object[]> list = (List<Object[]>) runner.query(sql,
				new ArrayListHandler());
		for (Object[] array : list) {
			System.out.print("编号 : " + array[0] + "\t");
			System.out.println("用户名 : " + array[1]);
		}
	}

	@Test
	public void testMapHandler() throws SQLException {
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from userInfo";
		Map<String, Object> map = runner.query(sql, new MapHandler());
		System.out.println("用户名:" + map.get("username"));
	}

	@Test
	public void testMapListHandler() throws SQLException {
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select * from userInfo";
		List<Map<String, Object>> list = runner
				.query(sql, new MapListHandler());
		for (Map<String, Object> map : list) {
			System.out.println("用户名:" + map.get("username"));
			System.out.println("薪水:" + map.get("salary"));
		}
	}

	@Test
	public void testScalarHandler() throws SQLException {
		QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
		String sql = "select count(*) from userInfo";
		Long sum = (Long) runner.query(sql, new ScalarHandler());
		System.out.println("共有" + sum + "人");
	}

}
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQL: String Data Types and ENUMs?MySQL: String Data Types and ENUMs?May 13, 2025 am 12:05 AM

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

MySQL BLOB: how to optimize BLOBs requestsMySQL BLOB: how to optimize BLOBs requestsMay 13, 2025 am 12:03 AM

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools