Java JDBC thows com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException for \'Test1\' value

时间:2017-11-13 06:26:46

标签: java mysql jdbc

I have below table: dummy_tbl

  |id |Name |
  ----------
  |1  |Test1|
  |2  |Test2|

When I try to execute below query in SQlyog - MySql(5.6.80) it's working fine:

 select * from dummy_tbl where name like \'Test1\';

But same query when I tried from code using JDBC statement it's throwing below error:

 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '\'Test1\'' at line 1

Code snipped from code:

  String sql = "SELECT * from dummy_tbl where name like \'Test1\'"; 
  Statement stmt= conn.createStatement(); 
  ResultSet rs = stmt.executeQuery(sql);

3 个答案:

答案 0 :(得分:1)

如上所述,陈述应该是

select * from dummy_tbl where name like 'Test%'

但它被“消毒”添加反斜杠。

在这种情况下使用PreparedStatement - 无论如何都是正确的方式(逃避自身,反对SQL注入):

String sql = "select * from dummy_tbl where name like ?";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
    stmt.setString(1, "Test%");
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            ...
        }
    }
}

答案 1 :(得分:0)

Changing the query to: select * from dummy_tbl where name like 'Test%';

should fix your issue.

答案 2 :(得分:-3)

try this once

select * from dummy_tbl where name like \\'Test\\';