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

</pre><pre>
 
 
 
 

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,V,...>中的泛型参数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;i++){
					preparedStatement.setObject(i+1, args[i]);
				}
			}
			return preparedStatement.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}finally {
			JDBCUtils.releaseConnection(connection, preparedStatement, null);
		}
	}

	/**
	 * 查询
	 * @param clazz
	 * @param sql
	 * @param args
	 * @return
	 */
	public  List<T> 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 < args.length; i++) {
					preparedStatement.setObject(i + 1, args[i]);
				}
			}

			resultSet = preparedStatement.executeQuery();
			
			//2处理结果解,得到Map的list,其中一个Map对象就是一条记录。
			//Map的key为resultSet中的列的别名,Map的value为列的值
			List<Map<String, Object>> values = 
					handleResultSetToMapList(resultSet);
			
			//3.把List<Map<String,Object>> 转化成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<String, 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<String, Object>> handleResultSetToMapList(
			ResultSet resultSet) throws SQLException {
		
		List<Map<String, 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 < rsmd.getColumnCount(); i++) {
			labels.add(rsmd.getColumnLabel(i + 1));
		}

		return labels;
	}
	public int getCount(String sql,String...id){
		Connection connection=null;
		ResultSet resultSet=null;
		PreparedStatement preparedStatement=null;
		try {
			 connection=JDBCUtils.getConnection();
			 resultSet=null;
			 preparedStatement=connection.prepareStatement(sql);
			if(id!=null&&id.length>0){
				for(int i=1;i<=id.length;i++)
				preparedStatement.setString(i, id[i-1]);
			}
			resultSet=preparedStatement.executeQuery();
			if(resultSet.next()){
				return resultSet.getInt(1);
			}
			else {
				return 0;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return 0;
		}finally{
			JDBCUtils.releaseConnection(connection, preparedStatement, resultSet);
		}
	}
	
}


定义ManagerDaoImpl,该类继承与Dao

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

}


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

导入的包

Java JDBC基本操作(增,删,该,查)总结_第1张图片

你可能感兴趣的:(jdbc,java数据库连接,java增删改查基本操作,java数据源配置,月夜归醉)