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

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

WBOY
Release: 2016-06-07 14:51:07
Original
1242 people have browsed it

/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

导入的包


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template