2017-04-23 88 views
0

請幫助解決下面提到的錯誤:MySQL錯誤時,選擇像

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:您的SQL語法錯誤;檢查對應於你的MySQL服務器版本正確的語法使用近「r.Username LIKE '%usernameanswer%' 和r.Createtime>手動NOW() - 間隔30秒

代碼

public List <CorrekctanswerModel> answerlist(String usernameanswer) throws Exception { 
     log.info("daomimpl" + usernameanswer); 
    List<CorrekctanswerModel> answerarray = new ArrayList<CorrekctanswerModel>(); 

    Connection c = null; 
    PreparedStatement ps = null; 
    ResultSet rs = null; 

    String sql = " select s.NAME as Subject, d.value as variant, r.Username, r.UserAnswer, r.Correctanswer, r.Createtime from resultlog r " + 

       " inner join test_table t on t.ID = r.QuestionId " + 

       " inner join subject s on s.ID= t.SUBJECT " + 

       " inner join dictionary d on d.ID = t.Variant" + 

       "where r.Username LIKE '%usernameanswer%' and r.Createtime > NOW() - INTERVAL 30 SECOND " ; 

    try { 

     c = DbHelper.getConnection(); 

     if (c != null) { 

      ps = c.prepareStatement(sql); 

      rs = ps.executeQuery(); 



      while (rs.next()) { 

       CorrekctanswerModel rep = new CorrekctanswerModel(); 
       rep.setSubject(rs.getString("Subject")); 
       rep.setVariant(rs.getString("variant")); 
       rep.setUsername(rs.getString("Username")); 
       rep.setUseranswer(rs.getString("UserAnswer")); 
       rep.setCorrekctanswer(rs.getString("Correctanswer")); 
       rep.setCreatedate(rs.getDate("Createtime")); 


        answerarray.add(rep); 


      } 
     } 

    } catch (Exception ex) { 
     ex.printStackTrace(); 


    } finally { 
     JdbcUtility.close(c, ps, rs); 
    } 

    return answerarray; 
} 
+1

請分享完整的SQL語句,否則我們可能無法完全爲您調試它。 –

+0

我已添加完整的代碼。在日誌中,你會看到我獲得「usernameanswer」。但我不能在sql中使用。 –

+2

在'where'之前放置一個空格,如下所示:'「其中r.Username LIKE'%usernameanswer%'...」'。然而,你真正需要的是哪裏?'用戶名LIKE'%「+ usernameanswer +」%'和...「' – zedfoxus

回答

1

我要添加爲以防有人絆倒在這個問題的答案...

在你的代碼,用這些行生成的SQL:

String sql = " select <fields> from resultlog r " + 
      " inner join test_table t on t.ID = r.QuestionId " + 
      " inner join subject s on s.ID= t.SUBJECT " + 
      " inner join dictionary d on d.ID = t.Variant" + 
      "where r.Username LIKE '%usernameanswer%' and ... " ; 

where之前應該有一個空格或之後有一個空格。在其目前的形式,查詢將做到這一點:

... inner join dictionary d on d.ID = t.Variantwhere r.Username ... 

where前添加一個空格,像這樣:

String sql = " select <fields> from resultlog r " + 
      " inner join test_table t on t.ID = r.QuestionId " + 
      " inner join subject s on s.ID= t.SUBJECT " + 
      " inner join dictionary d on d.ID = t.Variant" + 
      " where r.Username LIKE '%usernameanswer%' and ... " ; 

將導致您的查詢寫成這樣:

... inner join dictionary d on d.ID = t.Variant where r.Username ... 

而且,它看起來像usernameanswer是一個變量。如果是,where子句將如下所示:

   " where r.Username LIKE '%" + usernameanswer + "%' and ... " ;