当前位置:Gxlcms > mysql > JavaJDBC基本操作(增,删,该,查)总结

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

时间:2021-07-01 10:21:17 帮助过:32人阅读

/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 
 */
public class DAO {//带泛型的基类,派生类可以带具体beans泛型参数继承该类

	public Class 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)】带具体泛型的基类 或者获取此类的基类(Object),简单的讲就是谁继承Dao这个类后,在加载的时候,就会来加载这个构造函数。加载class的对象为Dao的派生类。派生类的基类就是Dao,并能获取基类带有的具体泛型。
		JDK文档描述是这样的:返回表示此Class所表示的实体(类、接口、基本类型或 void)的直接超类的Type。如果超类是参数化类型,则返回的对象必须准确反映源///代码中所使用的实际类型参数。
		所以最终打印为**/
		ParameterizedType parameterizedType=(ParameterizedType)type;//ParameterizedType 表示参数化类型,如 Collection。
		System.out.println(parameterizedType);
		Type[] ars=parameterizedType.getActualTypeArguments();/**返回表示此类型实际类型参数的对象的数组。就是返回Collection中的泛型参数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 getForList(String sql, Object... args) {

		List 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> values = 
					handleResultSetToMapList(resultSet);
			
			//3.把List> 转化成Class对象(clazz)的实例集List
			list = transfterMapListToBeanList( values);

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

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

		List result = new ArrayList<>();

		T bean = null;

		if (values.size() > 0) {
			for (Map m : values) {
				bean = clazz.newInstance();
				for (Map.Entry 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> handleResultSetToMapList(
			ResultSet resultSet) throws SQLException {
		
		List> values = new ArrayList<>();
		//获取列名
		List columnLabels = getColumnLabels(resultSet);
		Map 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 getColumnLabels(ResultSet rs) throws SQLException {
		List 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 {

	@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 {
			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

导入的包

人气教程排行