1

I am trying to compile a java file in the format:

PreparedStatement var = con.prepareStatement("SELECT * FROM table WHERE column LIKE '%?%';");

var.setString(1, string);
var.executeQuery();

However, it is not compiling, with the following errors. Can anyone explain why I am getting these errors?

BookPurchase.java:97: error: unreported exception SQLException; must be caught or declared to be thrown
            con.prepareStatement(
                                ^
BookPurchase.java:100: error: unreported exception SQLException; must be caught or declared to be thrown
            searchResults.setString(1, keyword);
                                   ^
BookPurchase.java:101: error: unreported exception SQLException; must be caught or declared to be thrown
            searchResults.executeQuery();
Bob
  • 7
  • 1
  • 6
  • 1
    Unrelated, but: `LIKE '%?%'` will not work. Read the JDBC tutorial to find out how to properly use a prepared statement parameter: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html –  Nov 17 '15 at 11:41

2 Answers2

4

That is because the prepareStatement is declared to throw an Exception.

To overcome your problem enclose your code in a try / catch block:

try {
    PreparedStatement prepStmt = con.prepareStatement(mySql);
    var.setString(1, string);
    var.executeQuery();
}catch(SQLException ex){
    //deal with exception
}

or you can make your method that executes this code throw an Exception:

public void myMethod() throws SQLException {
    ...
    ...
    PreparedStatement prepStmt = con.prepareStatement(mySql);
    var.setString(1, string);
    var.executeQuery();
    ...
    ...
}

This is the most basic on exception-handling in java. You can refer here for more info

MaVRoSCy
  • 17,747
  • 15
  • 82
  • 125
-1

Try that:

SELECT * FROM table WHERE column LIKE = ?;

then, set String as: var.setString(1, "%"+string+"%");

It should work fine.

Look also here: Using "like" wildcard in prepared statement

Community
  • 1
  • 1
m.aibin
  • 3,528
  • 4
  • 28
  • 47
  • 1
    You are right, but that has nothing to do with the compiler errors which the question is about - but it will lead to the next question. –  Nov 17 '15 at 11:39