Java数据库通用查询及封装(3)

import Java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommonEntity_DataProcesser {
private Connection connection = null;
private PreparedStatement pStatement = null;
private ResultSet resultSet = null;
private static DBHelp db = new DBHelp();
@SuppressWarnings("unchecked")
public <T extends Object> List<T> getEntityList(T entity, String sql,
Object... obj) {
List<T> list = new ArrayList<T>();
try {
connection = db.getConnection();
pStatement = connection.prepareStatement(sql);
pStatement = formatSql(pStatement, obj);
resultSet = pStatement.executeQuery();
ResultSetMetaData rsmd = resultSet.getMetaData();
String[] columnsName = getColumnName(rsmd);
Class clazz = entity.getClass();
Object entityObject = null;
Field[] fields = clazz.getDeclaredFields();
while (resultSet.next()) {
entityObject = clazz.newInstance();
for (int i = 0; i < columnsName.length; i++) {
for (int k = 0; k < fields.length; k++) {
if (fields[k].getName().equals(columnsName[i])) {
fields[k].setAccessible(true);
fields[k].set(entityObject, resultSet.getString(columnsName[i]));
}
}
}
list.add((T)entityObject);
}

} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}finally{
db.closeResource(connection, pStatement, resultSet);
}
return list;
}

private String[] getColumnName(ResultSetMetaData rsmd) {

String[] columnName = null;
try {
columnName = new String[rsmd.getColumnCount()];
for (int i = 0; i < rsmd.getColumnCount(); i++) {
columnName[i] = rsmd.getColumnName(i + 1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return columnName;
}

private PreparedStatement formatSql(PreparedStatement pStatement,
Object... obj) {
try {
if (obj.length != 0) {
for (int i = 1; i <= obj.length; i++) {
pStatement.setObject(1, obj[i]);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return pStatement;
}
}


Test1.java

import java.util.Date;
import java.util.List;
public class Test1 {
public static void main(String[] args) {
String sql="select * from students";
Date d3 = new Date();
CommonEntity_DataProcesser cedp = new CommonEntity_DataProcesser();
List<Students> list1 = cedp.getEntityList(new Students(), sql);
for (Students s : list1) {
System.out.println(s.getId() + "  " + s.getUserName() + "  "
+ s.getUserPass() + "  " + s.getUserSex());
}
Date d4 = new Date();
System.out.println(d4.getTime() - d3.getTime());
}
}

实体类students.Java

public class Students {
private String id;
private String userName;
private String userPass;
private String userSex;
getter….setter…();…
}


两种查询的性能差不多,能做到通用只不过是利用的泛型和集合的一些特性。。。文章只是为了复习来用,新手也可以看看吧,大牛飘过。。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwpfsz.html