1. 不借助实体类作为载体,封装数据。
Connections_DataProcesser.Java处理sql语句
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.HashMap;
import java.util.List;
import java.util.Map;
public class Connections_DataProcesser {
private Connection connection = null;
private PreparedStatement pStatement = null;
private ResultSet resultSet = null;
private static DBHelp db=new DBHelp();
public List<List<Map<String, String>>> getObjectList(String sql,Object...obj){
List<List<Map<String, String>>> list=new ArrayList<List<Map<String, String>>>();
List<Map<String, String>> mList=null;
Map<String, String> map=null;
try {
connection=db.getConnection();
pStatement=connection.prepareStatement(sql);
pStatement = formatSql(pStatement, obj);
resultSet=pStatement.executeQuery();
ResultSetMetaData rsmd=resultSet.getMetaData();
String[] columnName=getColumnName(rsmd);
while(resultSet.next()){
mList=new ArrayList<Map<String,String>>();
for(int i=0;i<rsmd.getColumnCount();i++){
map=new HashMap<String, String>();
map.put(columnName[i], resultSet.getString(i+1));
mList.add(map);
}
list.add(mList);
}
} catch (SQLException 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;
}
}
一个示范查询,这种封装查询要求对java的集合类比较熟悉
Test.java
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
String sql="select * from students";
Date d1=new Date();
Connections_DataProcesser dp=new Connections_DataProcesser();
List<List<Map<String, String>>> list=dp.getObjectList(sql);
for(int i=0;i<list.size();i++){
List<Map<String, String>> l=list.get(i);
for(int k=0;k<l.size();k++){
Set<Map.Entry<String, String>> mapset=l.get(k).entrySet()
Map.Entry<String, String> m= (Entry<String, String>) mapset.toArray()[0];
//System.out.print(m.getKey()+"="+m.getValue()+" ");
System.out.print(m.getValue()+" ");
}
System.out.println();
}
Date d2=new Date();
System.out.println(d2.getTime()-d1.getTime());
}
}