0

i am getting below exception

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 '?http://www.andhrabhoomi.net/' at line 1

I am trying to check whether a string exists in my data base or not

MY CODE:

               sql = "SELECT url FROM data where url = ?"+ "string";
                ResultSet rs = statement.executeQuery(sql);
                System.out.println(rs); 
Labeo
  • 5,831
  • 13
  • 47
  • 77
  • 1
    resulting `sql` becomes `SELECT url FROM data where url = ?string`, which is not valid ("?string" is not a part of SQL grammar nor a literal) – Alex Salauyou Mar 22 '16 at 05:43
  • Are you using Statement or PreparedStatement? Please go through : http://www.tutorialspoint.com/javaexamples/jdbc_prepared_statement.htm – Suyash Mar 22 '16 at 05:44
  • also if you were doing it the bad way above, the string would need to be quoted. – Scary Wombat Mar 22 '16 at 05:46

2 Answers2

2

Since you do have ? parameter marker, it would appear that you were attempting to use PreparedStatement, as you should, all assuming that the "string" is a sanitized example of an actual value to be used where ? is.

This is how a PreparedStatement should be done:

String sql = "SELECT url FROM data where url = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
    stmt.setString(1, "string");
    try (ResultSet rs = stmt.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString("url"));
        }
    }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247
  • still getting same error – Labeo Mar 22 '16 at 06:22
  • my code : String url1 = " asssa"; sql = "SELECT url FROM data where url = ?"; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, url1); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString("url")); } – Labeo Mar 22 '16 at 06:22
  • Remove `sql` from the `executeQuery()` call. – Andreas Mar 22 '16 at 06:23
0

Apply this on your try block

ps = conn.prepareStatement("SELECT url FROM data WHERE url = '?' + string");
ps.setString(1, THE VARIABLE ON WHERE YOU ARE GETTING THE VALUE OF URL);
rs = ps.executeQuery();