search
HomeDatabaseMysql TutorialJava JDBC基本操作(增,删,该,查)总结

/prepre package trade.axht.java.dao;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.dbutils.QueryRunner;import trade.axht.java.conn.JDBCUtils;import java.util.*;import java.lang.reflect.*;import java.sql.*;/** * *基





package trade.axht.java.dao;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;

import trade.axht.java.conn.JDBCUtils;

import java.util.*;
import java.lang.reflect.*;
import java.sql.*;
/**
 * 
*基类带泛型,派生类可以带泛型参数继承该类,通过反射对Beans对象操作
 * @author Administrator
 *
 * @param <t>
 */
public class DAO<t> {//带泛型的基类,派生类可以带具体beans泛型参数继承该类

	public Class<t> clazz;
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public DAO(){
	
		System.out.println(getClass()); //打印class trade.axht.java.dao.userImpl.****DaoImpl
		Type type=getClass().getGenericSuperclass();  
		System.out.println(type);
		/**获取继承【该类(DAO<t>)】带具体泛型的基类 或者获取此类的基类(Object),简单的讲就是谁继承Dao<t>这个类后,在加载的时候,就会来加载这个构造函数。加载class的对象为Dao<t>的派生类。派生类的基类就是Dao<t>,并能获取基类带有的具体泛型。
		JDK文档描述是这样的:返回表示此Class所表示的实体(类、接口、基本类型或 void)的直接超类的Type。如果超类是参数化类型,则返回的对象必须准确反映源///代码中所使用的实际类型参数。
		所以最终打印为**/
		ParameterizedType parameterizedType=(ParameterizedType)type;//ParameterizedType 表示参数化类型,如 Collection<string>。
		System.out.println(parameterizedType);
		Type[] ars=parameterizedType.getActualTypeArguments();/**返回表示此类型实际类型参数的对象的数组。就是返回Collection<t>中的泛型参数T,V类型的Type表示形式。Type 是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。**/
		System.out.println(ars);
		clazz=(Class) ars[0];//获取泛型参数的第一个Class对象
		System.out.println(clazz);
	//	System.out.println(clazz);
	}
	/**
	 * 增,删,改操作
	 * @param sql
	 * @param args
	 * @return
	 */
	public  int executeUpdate(String sql,Object...args){
		Connection connection=JDBCUtils.getConnection();
		PreparedStatement preparedStatement=null;
		try {
			preparedStatement=connection.prepareStatement(sql);
			if(args!=null&&args.length>0){
				for(int i=0;i<args.length preparedstatement.setobject args return preparedstatement.executeupdate catch e todo auto-generated block e.printstacktrace jdbcutils.releaseconnection preparedstatement null clazz sql public list> getForList(String sql, Object... args) {

		List<t> list = new ArrayList();

		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;

		try {
			//1. 得到结果集
			connection = JDBCUtils.getConnection();
			preparedStatement = connection.prepareStatement(sql);
			if(args!=null&&args.length>0){
				for (int i = 0; i > values = 
					handleResultSetToMapList(resultSet);
			
			//3.把List<map>> 转化成Class对象(clazz)的实例集List<t>
			list = transfterMapListToBeanList( values);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCUtils.releaseConnection(connection,preparedStatement,resultSet);
		}

		return list;
	}
	
	
	public List<t> transfterMapListToBeanList(List<map object>> values) throws InstantiationException,
			IllegalAccessException, InvocationTargetException {

		List<t> result = new ArrayList();

		T bean = null;

		if (values.size() > 0) {
			for (Map<string object> m : values) {
				bean = clazz.newInstance();
				for (Map.Entry<string object> entry : m.entrySet()) {
					String propertyName = entry.getKey();
					Object value = entry.getValue();
					//利用org.apache.commons.beanutils.BeanUtils工具类反射设置对象属性
					BeanUtils.setProperty(bean, propertyName, value);
					
				/*	try {
						ReflectorUtil.setProperty(bean, propertyName, value);
					} catch (NoSuchFieldException | SecurityException | IllegalArgumentException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
				}
				result.add(bean);
			}
		}

		return result;
	}
	
	
	public List<map object>> handleResultSetToMapList(
			ResultSet resultSet) throws SQLException {
		
		List<map object>> values = new ArrayList();
		//获取列名
		List<string> columnLabels = getColumnLabels(resultSet);
		Map<string object> map = null;
		while (resultSet.next()) {
			map = new HashMap();

			for (String columnLabel : columnLabels) {
				Object value = resultSet.getObject(columnLabel);
				map.put(columnLabel, value);
			}
			values.add(map);
		}
		return values;
	}
	
	private  List<string> getColumnLabels(ResultSet rs) throws SQLException {
		List<string> labels = new ArrayList();

		ResultSetMetaData rsmd = rs.getMetaData();
		for (int i = 0; i 0){
				for(int i=1;i<br>
<br>

<p>定义ManagerDaoImpl,该类继承与Dao</p>
<p></p>
<pre code_snippet_id="1676743" snippet_file_name="blog_20160509_9_8230022" name="code" class="html">package trade.axht.java.dao.userImpl;

import trade.axht.java.dao.DAO;
import trade.axht.java.dao.ManagerDAO;
import trade.axht.java.domain.Manager;

public class ManagerDaoImpl  extends DAO<manager> {

	@Override
	public int getCount(Manager manager) {
		// TODO Auto-generated method stub
		String sql="select Count(*) from tb_manager where username=? and password=?";
		return getCount(sql, manager.getUsername(),manager.getPassword());
	
	}

}
</manager>


Beans类型的Manager类

package trade.axht.java.domain;

public class Manager {
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Manager() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Manager(int id, String username, String password) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
	}
	
}

数据库连接操作类

package trade.axht.java.conn;

import javax.sql.*;
import java.sql.*;
import java.util.*;
import java.io.*;

public class JDBCUtils {
	private static DataSource  dataSource=null;

	static{                                                                                                                                                                                                           
		Properties properties=new Properties();
		InputStream in=JDBCUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");//加载配置文件
		try {
		<span style="white-space:pre">	</span>properties.load(in);
		
			dataSource=org.apache.commons.dbcp2.BasicDataSourceFactory.createDataSource(properties);//利用数据库连接池(dbcp2)获取数据源
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("数据库连接出错!");
			e.printStackTrace();
		}
	}
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			
			e.printStackTrace();
			return null;
		}
	}
	public static void releaseConnection(Connection connection,Statement statement,ResultSet resultSet) {
		if (connection!=null) {
			try {
				connection.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (statement!=null) {
			try {
				statement.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (resultSet!=null) {
			try {
				resultSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

数据库配置文件 jdcp.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/blog
username=root
password=brozer
initialSize=5
maxIdle=10
maxTotal=50
maxWaitMillis=5000
minIdle=5

导入的包


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
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

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.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

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.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

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: 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

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 Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment