search
HomeDatabaseMysql Tutorialjava自学之路-----jdbc_框架

jdbc框架{ 元数据: 数据库、表、列的定义信息在框架中才涉及到的知识 DataBaseMetaData对象(数据库){ 获取方法: connection.getMetaData(); 使用: getURL();返回当前连接的数据库的URL信息 getUserName();返回当前连接的数据库的用户名 getDatabaseProd

jdbc框架{

元数据:数据库、表、列的定义信息——在框架中才涉及到的知识

DataBaseMetaData对象(数据库){

获取方法:connection.getMetaData();

使用:

getURL();——返回当前连接的数据库的URL信息

getUserName();——返回当前连接的数据库的用户名

getDatabaseProductName();——数据库的产品名称

getDatabaseProductVersion();——数据库的版本号

getDriverName();——驱动程序的名称

getDriverVersion();——驱动程序的版本号

isReadOnly();——指示数据库是否只允许读的操作

...

例:

	Connection conn = JdbcUtils.getConnection();
	DatabaseMetaData md = conn.getMetaData();
	System.out.println(md.getURL());//输出:jdbc:mysql://localhost:3306/mydb
	System.out.println(md.getDatabaseProductName());//输出:MySQL
	System.out.println(md.getDriverVersion());//输出:mysql-connector-java-5.1.22 ( Revision: ${bzr.revision-id} )

}

ParameterMetaData(参数){

获取方法:preparedStatement.getParameterMetaData();——例如一条select * from user where name=? and password=?;这个对象就是这条sql语句参数(问号)的元数据

使用:

getParameterCount();——获得指定参数的个数

getParameterType(int param);——指定参数的sql类型

...

例:

		Connection conn = JdbcUtils.getConnection();
		String sql = "insert into user(id,name) values(?,?)";
		PreparedStatement st = conn.prepareStatement(sql);
		ParameterMetaData md = st.getParameterMetaData();
		System.out.println(md.getParameterCount());//输出:2
//		System.out.println(md.getParameterType(1));该方法由于mysql的驱动不支持,会抛异常

}

ResultSetMetaData(结果集){

获取方法:resultSet.getMetaData();——获得代表结果集ResultSet对象的元数据,告诉用户结果集的一些信息

使用:

getColumnCount();——结果集对象的列数

getColumnName(int column);——指定列的名称

getColumnTypeName(int column);——指定列的类型

...

例:

		Connection conn = JdbcUtils.getConnection();
		String sql = "select * from user";
		PreparedStatement st = conn.prepareStatement(sql);
		ResultSet rs = st.executeQuery();
		ResultSetMetaData md = rs.getMetaData();
		System.out.println(md.getColumnCount());//输出:一共有多少列
		System.out.println(md.getColumnName(1));//输出:第一列的列名
		System.out.println(md.getColumnType(1));//输出:第一列的类型

}

编写增删改查的框架(方法){

//增删改的工具方法,只需要将sql语句和sql中的问号对应的参数用数组形式传进方法,就可以执行成功
	public static void update(String sql, Object params[]) throws SQLException {
//		定义基本对象
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			st = conn.prepareStatement(sql);
//			根据传进来的参数数组填充sql中的问号
			for (int i = 0; i < params.length; i++) {
				st.setObject(i+1, params[i]);
			}
			st.executeUpdate();
		}finally{
			JdbcUtils.release(conn, st, rs);
		}
		
	} 
	
//	查的工具方法,还要得到一个用户想要处理结果集的类,用户只需要new一个处理类的对象进来即可
	public static Object query(String sql, Object params[], ResultSetHandler handler) throws SQLException{
//		定义基本对象
		Connection conn = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			st = conn.prepareStatement(sql);
//			根据传进来的参数数组填充sql中的问号
			for (int i = 0; i < params.length; i++) {
				st.setObject(i+1, params[i]);
			}
//			由于这边得到的结果集有些内容都不知,可以向用户暴露一个处理接口的方法,然后直接在该程序中调用这个处理的方法。
//			用户实现了这个接口并做出了想要的处理,传递到本程序中,就能返回用户想用的数据
			rs = st.executeQuery();
			return handler.handler(rs);
		}finally{
			JdbcUtils.release(conn, st, rs);
		}
	}
}
//	定义接口
	interface ResultSetHandler{
		public abstract Object handler(ResultSet rs);
	}

//实现处理单行数据的类,返回封装了结果数据的对象,如果需要处理的是多行的数据,就需要使用集合,把每行数据封装成对象,再存入集合。那么这个方法返回的就是集合对象
class BeanHandler implements ResultSetHandler{
//	通过构造函数获得对象的字节码,以备将结果集存到该对象中
	private Class clazz = null;
	
	public BeanHandler(Class clazz) {
	super();
	this.clazz = clazz;
	}
	@Override
	public Object handler(ResultSet rs) {
		try {
			if(rs.next()){
				return null;
			}
//			创建封装结果集的bean对象
			Object bean = clazz.newInstance();
//			通过元数据的技术得到结果集的内容
			ResultSetMetaData md = rs.getMetaData();
			for (int i = 0; i < md.getColumnCount(); i++) {
//				获取结果集每列的名称
				String columnName = md.getColumnName(i+1);
//				得到该列的值
				Object value = rs.getObject(columnName);
//				为bean对象里的列名对应的属性赋value,使用反射技术;也可以使用beanutils库,这样就必须导入一个库,不方便
				//获取bean里的属性,需要设置为私有可见
				Field f = bean.getClass().getDeclaredField(columnName);
				f.setAccessible(true);
				//进行赋值
				f.set(bean, value);	
			}
			return bean;
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

}

开源框架dbutils{

1.commons-dbutils是Apache组织提供的一个开源jdbc工具类库,他是对jdbc的简单封装,使用dbutils能极大简化jdbc编码的工作量同时也不会影响程序性能

2.使用dbutils需要查看api文档,内部主要是两个类QueryRunner(用于增删改查)和ResultSetHandler(用于处理查询的结果集)

例:

	public void add(){
		try {
	//	使用QueryRunner和ResultSetHandler
	//	创建一个Queryrunner对象,将数据库的数据源作为构造函数传入
				QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
	//	定义sql语句和参数对象
				String sql = "insert into user(id,name) values(?,?)";
				Object params[] = {"1", "aaa"};
	//	执行更新操作,将sql和参数传入
				runner.update(sql, params);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public void query(){
		try {
//	使用QueryRunner和ResultSetHandler
//	创建一个Queryrunner对象,将数据库的数据源作为构造函数传入
			QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
//	定义sql语句和参数对象
			String sql = "select * from user";
//	执行更新操作,将sql传入.并且将结果处理到list容器中
			List<User> list = runner.query(sql, new BeanListHandler<User>(User.class));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
结果集处理器(ResultSetHandler实现类){

ArrayHandler:把结果集的第一行数据封装到一个数组内,返回数组对象。——new ArrayHandler();

ArrayListHandler:把结果集的每一行数据都封装到一个数组中,再将每个数组存到list集合内,返回list对象。——new ArrayListHandler();

BeanHandler:将结果集的第一行数据封装到一个bean对象中,需要将bean的字节码对象传入,返回bean对象。——new BeanHandler(User.class);

BeanListHandler:将结果集的每一行数据封装到一个bean对象中,再存放在list集合内,同样需要传入bean的字节码对象,返回list对象。——new BeanListHandler(User.class);

ColumnListHandler:将结果集的某一列的数据存放在list中,需要将列名传入,返回list对象。——new ColumnListHandler("id");

KeyedHandler:将结果集的每一行数据都封装到一个map(key为列名,value为该列的值)中,再将这个map存放在另一个map中(key为传入的指定列名的值,value就是map),返回map对象。——new KeyedHandler("id");

MapHandler:将结果集的第一行数据封装到一个map中,key为列名,value为该列的值,返回map对象。——new MapHandler();

MapListHandler:将结果集的每一行数据都封装到一个map中,再存放在list中,返回list对象。——new MapListHandler();

ScalarHandler:将制定的第一行的某一列(可以传入第几列或者列名)的值存放在一个对象内,返回该对象。——new ScalarHandler(1);

例:

			//查询总记录数
			QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
			String sql = "select count(*) from user";
////	1.使用arrayhandler处理器
//			Object result[] = runner.query(sql, new ArrayHandler());
////			取出数据,取出的是Long型的数据,需要进行转型
//			int count = ((Long)result[0]).intValue();
//	2.使用scalarhandler处理器,取出第一列的值,指定了封装到Long对象中,进行转型
			int count = runner.query(sql, new ScalarHandler<Long>(1)).intValue();

}

}

}

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: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

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: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

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: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

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.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

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.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

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

MySQL's Role: Databases in Web ApplicationsMySQL's Role: Databases in Web ApplicationsApr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

MySQL: Building Your First DatabaseMySQL: Building Your First DatabaseApr 17, 2025 am 12:22 AM

The steps to build a MySQL database include: 1. Create a database and table, 2. Insert data, and 3. Conduct queries. First, use the CREATEDATABASE and CREATETABLE statements to create the database and table, then use the INSERTINTO statement to insert the data, and finally use the SELECT statement to query the data.

MySQL: A Beginner-Friendly Approach to Data StorageMySQL: A Beginner-Friendly Approach to Data StorageApr 17, 2025 am 12:21 AM

MySQL is suitable for beginners because it is easy to use and powerful. 1.MySQL is a relational database, and uses SQL for CRUD operations. 2. It is simple to install and requires the root user password to be configured. 3. Use INSERT, UPDATE, DELETE, and SELECT to perform data operations. 4. ORDERBY, WHERE and JOIN can be used for complex queries. 5. Debugging requires checking the syntax and use EXPLAIN to analyze the query. 6. Optimization suggestions include using indexes, choosing the right data type and good programming habits.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.