小小的总结下

本文深入探讨了数据库查询的基础知识,包括如何使用tableName、fieldName、cond等关键元素进行查询,并详细解释了如何构建查询条件表达式。通过实例演示,帮助读者掌握数据库查询的核心技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

tableName代表数据库中的表
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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值