tableName代表数据库中的表
fieldName代表需要查询的数据库表中的列名
cond代表查询的条件表达式,
cond.getCondition()得到具体的表达式
查询函数
Condition类,构造条件表达式
Expression类代表任意的一个表达式
fieldName代表需要查询的数据库表中的列名
cond代表查询的条件表达式,
cond.getCondition()得到具体的表达式
查询函数
public static List<Map<String, Object>> query(Connection con,
String tableName, String[] fieldName, Condition cond){
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
PreparedStatement psmt = null;
ResultSet rs = null;
try{
StringBuffer sql = new StringBuffer("select ");
StringBuffer tobeQueryed = new StringBuffer();
if(fieldName.length!= 0){
for(String field : fieldName){
tobeQueryed.append(field + " ,");
}
tobeQueryed = new StringBuffer(tobeQueryed.substring(0, tobeQueryed.length()-1));
}else{
tobeQueryed.append(" * ");
}
sql.append(tobeQueryed);
sql.append(" from "+tableName+ " where ");
if (cond != null)
sql.append(cond.getCondition());
System.out.println("sql:"+sql);
psmt = con.prepareStatement(sql.toString());
//按照查询字段的数值设定,需要对应数据库中的类型!很重要的!
if( cond!=null ){
System.out.println(cond.getQueryValues());
Vector<Object> values = cond.getQueryValues();
int i = 1;
for(Object value : values){
if (value != null) {
psmt.setObject(i, value);
i++;
}
}
}
rs = psmt.executeQuery();
while (rs.next()) {
Map<String, Object> curResult = new HashMap<String, Object>();
for (int j = 0; j < fieldName.length; j++) {
Object object = rs.getObject(j + 1);
if ( object instanceof String && object !=null ){
curResult.put(fieldName[j], ((String)object).trim());
}
else{
curResult.put(fieldName[j], object);
}
}
result.add(curResult);
}
}catch(Exception e){
}
return result;
}
}
Condition类,构造条件表达式
Expression类代表任意的一个表达式
public class Condition {
private Vector<Expression> expressions = new Vector<Expression>();
private Vector<LogicOperator> operators = new Vector<LogicOperator>();
public void addExpression(Expression exp){
if(expressions.size()>0){
System.out.println("and");
operators.add(LogicOperator.and);
}
expressions.add(exp);
}
//得到查询字段对应的值
public Vector<Object> getQueryValues(){
Vector<Object> values = new Vector<Object>();
for(int i=0; i<expressions.size(); i++){
values.add(expressions.get(i).rightExp);
}
return values;
}
public String getCondition(){
String sql = "";
int i;
for(i=0; i<operators.size(); i++){
sql = sql + expressions.get(i).getSQL() + " "+Expression.LogicOperatorToString(operators.get(i))+ " ";
}
sql = sql + expressions.get(i).getSQL();
return sql;
}
}