0

In MYSQL database I have a table name search. When I write this query it executed successfully.

"select * from 'search' where path like %overview%"

But when I write it in java:

String query="SELECT path FROM `search` WHERE path like %?% ";
java.sql.PreparedStatement st=con.prepareStatement(query);
st.setString(1,textField.getText() );
ResultSet rs=st.executeQuery();

It's not working and displays an error:

com.mysql.jdbc.exception.jdbc4.MySQLSystaxErrorException: you have an error in sql syntax; check the manual that corresponds to your Mysql server version for the right Syntax to use near '%'overview'%' at line 1

spencer7593
  • 106,611
  • 15
  • 112
  • 140
Rakibul Hasan
  • 61
  • 2
  • 9

2 Answers2

4
String query="SELECT path FROM `search` WHERE path like ? ";
java.sql.PreparedStatement st=con.prepareStatement(query);
st.setString(1,"%"+ textField.getText() + "%" );
ResultSet rs=st.executeQuery();

You can try the above code

MrTux
  • 32,350
  • 30
  • 109
  • 146
Vigneshwaran
  • 387
  • 1
  • 2
  • 14
0

The percent signs are literals, if you want to include those in the SQL text, and have MySQL add those to the value you pass in, you could do something like this:

String query="SELECT path FROM `search` WHERE path LIKE CONCAT('%',?,'%')";

The other alternative is to remove the percent signs from the SQL text statement

String query="SELECT path FROM `search` WHERE path LIKE ?";

and then prepend/append percent characters to the value you supply.

spencer7593
  • 106,611
  • 15
  • 112
  • 140