Reputation: 7
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();
Upvotes: 1
Views: 5886
Reputation: 17859
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
Upvotes: 4
Reputation: 3603
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
Upvotes: -1