我有一个程序,它来自一个名为" Dishes"的表,它以一周中的日期作为列名,今天的菜。我从日历中获取Day的名称(它返回的名称如:Wednesday)但是当我在SQL部分中使用它时,在java中返回列的名称,而不是accuall索引。
String selectD="select ? as smt from DISHES where ESTID=?";
prestatement=dbConnection.prepareStatement(selectD);
//here sets the day from Calendar stuff. It seems OK. I get the right date, like "Wednesday" at wednesdays
prestatement.setString(1,day);
prestatement.setInt(2,resID);
rs=prestatement.executeQuery();
if(rs.next()){
String Dish =rs.getString("smt");
EstInfo.setText("Today's dish is "+Dish);
}else{
System.out.println("Found nothing in DISHES");
}
答案 0 :(得分:2)
您无法使用?
插入列名称。标记仅供参考。
您的查询相当于:
select 'Wednesday' as smt from DISHES where ESTID=42
这当然没有任何意义,可以返回这样的文字文字。
使用字符串连接来构建SQL,例如
String selectD = "select " + day + " as smt from DISHES where ESTID=?";
然后
setInt(1, resID);
答案 1 :(得分:0)
要在没有SQL注入的情况下执行此操作,您可以尝试以下操作:
String selectD="select case UPPER(?) " +
+ "when 'SUNDAY' then Sunday " +
+ "when 'MONDAY' then Monday " +
+ "when 'TUESDAY' then Tuesday " +
+ "when 'WEDNESDAY' then Wednesday " +
+ "when 'THURSDAY' then Thursday " +
+ "when 'FRIDAY' then Friday " +
+ "when 'SATURDAY' then Saturday " +
+ "end as smt from DISHES where ESTID=?";
prestatement=dbConnection.prepareStatement(selectD);
prestatement.setString(1,day);
prestatement.setInt(2,resID);
rs=prestatement.executeQuery();
if(rs.next()){
String Dish =rs.getString("smt");
EstInfo.setText("Today's dish is "+Dish);
}else{
System.out.println("Found nothing in DISHES");
}
祝你好运。