WHERE子句问题

时间:2016-01-17 23:08:01

标签: java sql prepared-statement

给出以下我要构造的SQL语句:

SELECT CONCAT(employees.first_name," ", employees.last_name), landlines.number
FROM employees,landlines WHERE employees.id=landlines.emp_id ORDER BY employees.last_name

最初使用问号参数创建它,如下所示:

SELECT CONCAT(employees.first_name," ", employees.last_name), landlines.number
FROM employees,landlines WHERE employees.id=? ORDER BY employees.last_name

从WHERE条件中可以看出,我使用来自固定电话表的字段引用了employees表中的字段。基本上是引用外键字段的主键字段。非常标准的东西。

我的问题是使用PreparedStatement类。我有一个方法,使用如下所示的开关案例:

PreparedStatement statement = ...;
...
//wc is a WhereCondition object and getValue() returns an Object which I cast to a particular type
Field.Type value = wc.getKey().getFieldType();
switch (value)
{
  case STRING:
      statement.setString(index, ((String)wc.getValue()));
      index++;
      break;
  case INT:
      if(wc.getValue() instanceof Field)
      {
        Field fld = (Field)wc.getValue();
        statement.setString(index,fld.toString());
      }
      else
        statement.setInt(index, ((Integer)wc.getValue()));
      index++;
      break;
  case FLOAT:
      statement.setFloat(index, ((Float)wc.getValue()));
      index++;
      break;
  case DOUBLE:
      statement.setDouble(index, ((Double)wc.getValue()));
      index++;
      break;
  case LONG:
      statement.setLong(index, ((Long)wc.getValue()));
      index++;
      break;
  case BIGDECIMAL:
      statement.setBigDecimal(index, ((BigDecimal)wc.getValue()));
      index++;
      break;
  case BOOLEAN:
      statement.setBoolean(index, ((Boolean)wc.getValue()));
      index++;
      break;
  case DATE:
      //We don't want to use the setDate(...) method as it expects
      //a java.sql.Date returned which doesn't allow for any time stamp.
      //Let the database perform the conversion from String to Date type.
      statement.setString(index, ((String)wc.getValue()));
      index++;
      break;
  case DBFUNCTION:
      statement.setString(index, ((String)wc.getValue()));
      index++;
      break;
  case IMAGE:
      statement.setString(index, ((String)wc.getValue()));
      index++;
      break;
}

如果你看一下INT,我试图通过测试类型Field来避免ClassCastException,从而调用statement.setString(index,fld.toString()。问题是我结束了SQL带有WHERE子句的语句,如下所示:

WHERE employees.id = 'landlines.emp_id'

那些讨厌的引号会阻止查询正确执行。有没有办法将字段employees.id的参数设置为INTXXX,这样可以在没有添加引号的情况下输入landlines.emp_id?

1 个答案:

答案 0 :(得分:1)

这将JOIN与参数分开。我无法在你的环境中测试它,所以我不确定它是否正确,但它不需要引号:

SELECT CONCAT(e.first_name," ", e.last_name), l.number
FROM employees e
JOIN landlines l ON e.id=l.emp_id
WHERE e.id=? ORDER BY e.last_name