所实现的功能差不多。这是第三方开发的,要导入相应的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); } }

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


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

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools