2016-09-30 124 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的类型不是字符串,你可以使用它来试试:“?”