欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据库查询的优化

程序员文章站 2022-06-02 12:53:35
...

查询一个实体的优化步骤:

1.创建gerRs(),参考代码如下

public static ResultSet getRs(String sql, Object[] args) {
		Object t = null;
		Connection con = getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		Dao d = new Dao();
		try {
			ps = con.prepareStatement(sql);
			for (int i = 0; i < args.length; i++) {
				if (args[i].getClass() == java.util.Date.class) {
					java.util.Date date = (java.util.Date) args[i];
					ps.setDate(i + 1, new java.sql.Date(date.getTime()));
				} else if (args[i].getClass() == boolean.class || args[i] == Boolean.class) {
					ps.setInt(i + 1, (boolean) args[i] == true ? 1 : 0);
				} else {
					ps.setObject(i + 1, args[i]);
				}
				ps.setString(i + 1, (String) args[i]);
			}
			rs = ps.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rs;
	}

2.创建封装实体的类,参考代码如下

package com.xxx.generic.demo;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;

public class BeanResultSetHandler<T> {
	private Class clazz;

	public BeanResultSetHandler(Class<T> clazz) {
		this.clazz = clazz;
	}

	public T handler(ResultSet rs) {
		T bean = null;
		try {
			if (rs.next()) {
				bean = (T) this.clazz.newInstance();
				ResultSetMetaData rsmd = rs.getMetaData();
				int totalColumns = rsmd.getColumnCount();
				Field[] fields = this.clazz.getDeclaredFields();
				for (Field f : fields) {
					String paramName = f.getName();
					for (int i = 1; i <= totalColumns; i++) {
						String columnName = rsmd.getColumnName(i);
						if (columnName.equals(paramName)) {
							Object columnValue = rs.getObject(columnName);
							f.setAccessible(true);
							if (f.getType() == java.lang.Boolean.class || f.getType() == boolean.class) {
								int n = Integer.parseInt((String) columnValue);
								f.set(bean, n == 0 ? true : false);
							} else if (f.getType() == Double.class || f.getType() == double.class) {
								f.set(bean, (double) columnValue);
							} else if (f.getType() == Float.class || f.getType() == float.class) {
								f.set(bean, (float) columnValue);
							} else {
								f.set(bean, columnValue);
							}
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtils.close(null, null, rs);
		}
		return bean;
	}
}

3.创建测试方法,参考代码如下

public void t2() {
		String sql = "select * from student where name=?";
		BeanResultSetHandler handler = new BeanResultSetHandler<>(Student.class);
		Student s = null;
		s = (Student) handler.handler(DbUtils.getRs(sql, new Object[] { "小张" }));
		System.out.println(s);
	}

4.相关说明

在getRs()方法中未曾释放相关的资源流。

相关标签: 数据库查询优化