2016-09-30 224 views
0

我在Java代碼中的SQL代碼,看起來像這樣:錯誤1064:SQL語法錯誤

Connection con = null; 
     PreparedStatement pstmt = null; 
     ResultSet rs = null; 
     beforeExerTestDTO dto = new beforeExerTestDTO(); 

     StringBuffer sql = new StringBuffer(); 
     sql.append(" select * "); 
     sql.append(" from n_before_exer "); 
     sql.append(" where id=?"); 
     sql.append(" and reg_date = (select max(reg_date) from n_before_exer where id=?)"); 

     try { 
      con = pool.getLocalConnection(); 
      pstmt = con.prepareStatement(sql.toString()); 
      pstmt.setString(1, id); 
      pstmt.setString(2, id); 
      System.out.println("여기까진 살까??"); 
      rs = pstmt.executeQuery(); 
      /...... 
      ...... some code/
      }catch(SQLException e){ 
      System.out.println("read : " + e); 
      System.out.println("read : " + sql); 
     }catch(Exception e){ 
      System.out.println("read : " + e.getStackTrace().toString()); 
     }finally{ 
      DBClose.close(con, pstmt, rs); 
     } 
     return dto; 
} 

當文件被執行它形成了這樣的說法在控制檯:

select * from n_before_exer where id=? and reg_date = (select max(reg_date) from n_before_exer where id=?) 

,並拋出一個

java.sql.SQLEXCEPTION

我試了一下:

  1. 我跑在MySQL Workbench中查詢相同:

,並得到了以下錯誤:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? and reg_date = (select max(reg_date) from n_before_exer where id=?)' at line 1

的研究課題顯示位:

  1. 這種方式是不是首選的方式,因爲它可能導致注入攻擊
  2. 並建議使用佔位符作爲參數

這似乎有點複雜,我,如果有人能幫助我建立這個說法在正確的首選方式,請

感謝

+0

你更換在執行查詢之前使用參數? –

+1

@DanteFañaBadia:在錯誤陳述中增加了額外的代碼。你能否看到它是否確認你在說什麼 –

+0

我認爲是一個帶參數的問題,參數顯然沒有設置正確嘗試放在'周圍? ,只是爲了調試建議。 –

回答

0

您應該使用一個事先準備好的聲明:

Connection con; // get a connection 
PreparedStatement ps = con.prepareStatement(sql); 
ps.setInt(1, someInt); 
ps.setInt(2, someOtherInt); 

ResultSet rs = ps.executeQuery(); 
while (rs.next()) { 
    // process each record 
} 
+0

我在SQL錯誤語句之前和之後添加了額外的代碼。我想我已經在做你所要求的。你可以看看更新後的問題。謝謝 –

+0

你在哪裏創建連接?我沒有看到這發生在任何地方。 –

0

您的語句在語法上看起來很正確。你有編碼問題,你的Java文件?

+0

Kevin文件使用UTF-8,但數據也可以是韓文。我猜這是以前的工作,只有在這個本地設置其行爲奇怪。 –

+0

我只是想你的SQL語句中是否有全角字符。 – Kevin

0

pstmt.setString(1,id);

我想這個問題是ID的類型不是字符串,你可以使用它來試試:「?」