在SQL查询的WHERE子句中有错误,

时间:2014-07-29 17:20:58

标签: java sql oracle

我在此代码中出错:

public List<AvailableTest> srchInTestsInDb(String search, String catg) {
    try 
     { 
         Connection conn = Dbconn.Connect();

         System.out.println(catg);

         String sql = "SELECT * "
                 + "FROM AVAILABLE_TESTS "
                 + "WHERE TST_CATAGORY="+catg+"";
                // + "TST_NAME LIKE '"+search+"%'";// AND TST_CATAGORY ="+catg+""; 

         Statement statement = conn.createStatement(); 
         ResultSet rs = statement.executeQuery(sql); 
         List<AvailableTest> testList = new ArrayList<AvailableTest>(); 
         while (rs.next()) 
         { 
            AvailableTest newtest = new AvailableTest(); 

            newtest.setTstNo(rs.getInt("TST_NO"));

            newtest.setTstName(rs.getString("TST_NAME"));

            newtest.setTstCatagory(rs.getString("TST_CATAGORY"));

            newtest.setTstNormalValue(rs.getString("TST_NORMALVAL"));

            testList.add(newtest); 
         } 
         return testList;
     } 
     catch (SQLException ex) 
     { 
         Logger.getLogger(DbHandeler.class.getName()).log(Level.SEVERE, null, ex);
         return null; 
     }
}

它的输出是:

chem
Jul 29, 2014 10:02:28 PM Db.DbHandeler srchInTestsInDb
SEVERE: null
java.sql.SQLSyntaxErrorException: ORA-00904: "CHEM": invalid identifier

当我打印&#34; catg&#34;它打印&#34;化学&#34;我在查询中需要它,但它不起作用。

3 个答案:

答案 0 :(得分:4)

它应该是WHERE TST_CATAGORY='"+catg+"'",因为String参数应该是引号。

那就是说,这是一个非常糟糕的做法,你冒着SQL注入的风险。使用准备好的声明:

String sql = "SELECT * "
                 + "FROM AVAILABLE_TESTS "
                 + "WHERE TST_CATAGORY=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString (1, catg);
ResultSet res = stmt.executeQuery ();;

答案 1 :(得分:0)

甲骨文正在考虑将CHEM列为一个名称,因为它没有被引用。要让Oracle将其视为字符串,请使用单引号。

String sql = "SELECT * "
+ "FROM AVAILABLE_TESTS "
+ "WHERE TST_CATAGORY='"+catg+"'";

答案 2 :(得分:0)

尝试:

String sql = "SELECT * "
                 + "FROM AVAILABLE_TESTS "
                 + "WHERE TST_CATAGORY='"+catg+"';";

由于catg的内容是String,因此它也应该用引号(在SQL-Query中)。