Home Database Mysql Tutorial Java JDBC基本操作(增,删,该,查)总结

Java JDBC基本操作(增,删,该,查)总结

Jun 07, 2016 pm 02:51 PM
java jdbc Basic operations Summarize

/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.*;/** * *基

Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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>
Copy after login


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;
	}
	
}
Copy after login

数据库连接操作类

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();
			}
		}
	}
}
Copy after login

数据库配置文件 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
Copy after login

导入的包


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles