简体   繁体   中英

Error 1064 : SQL syntax error

I have a SQL code in a java code which looks like this :

    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;
}

When the file gets executed it forms a statement like this in console:

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

and throws a

java.sql.SQLEXCEPTION

What I tried :

  1. I ran the same in Mysql Workbench query :

and got the following error:

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

A bit of research on the topic shows :

  1. This way is not a preferred way as it can lead to injection attacks
  2. And was advised to use a placeholder for a parameter

It seems a bit complex for me, if anyone can help me construct this statement in the right preferred way please

Thanks

You should be using a prepared statement:

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
}

Your statement seem correct in syntax. Are you have encoding issue on you java file?

pstmt.setString(1, id);

I guess the problem is that the type of id is not string ,you could use this to have a try:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM