DbUtils操作数据库
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 + "人"); } }

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

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

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











Apple's latest releases of iOS18, iPadOS18 and macOS Sequoia systems have added an important feature to the Photos application, designed to help users easily recover photos and videos lost or damaged due to various reasons. The new feature introduces an album called "Recovered" in the Tools section of the Photos app that will automatically appear when a user has pictures or videos on their device that are not part of their photo library. The emergence of the "Recovered" album provides a solution for photos and videos lost due to database corruption, the camera application not saving to the photo library correctly, or a third-party application managing the photo library. Users only need a few simple steps

To handle database connection errors in PHP, you can use the following steps: Use mysqli_connect_errno() to obtain the error code. Use mysqli_connect_error() to get the error message. By capturing and logging these error messages, database connection issues can be easily identified and resolved, ensuring the smooth running of your application.

How to use MySQLi to establish a database connection in PHP: Include MySQLi extension (require_once) Create connection function (functionconnect_to_db) Call connection function ($conn=connect_to_db()) Execute query ($result=$conn->query()) Close connection ( $conn->close())

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Using the database callback function in Golang can achieve: executing custom code after the specified database operation is completed. Add custom behavior through separate functions without writing additional code. Callback functions are available for insert, update, delete, and query operations. You must use the sql.Exec, sql.QueryRow, or sql.Query function to use the callback function.

Through the Go standard library database/sql package, you can connect to remote databases such as MySQL, PostgreSQL or SQLite: create a connection string containing database connection information. Use the sql.Open() function to open a database connection. Perform database operations such as SQL queries and insert operations. Use defer to close the database connection to release resources.

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.
