我正在尝试以以下格式编译java文件:
PreparedStatement var = con.prepareStatement("SELECT * FROM table WHERE column LIKE '%?%';");
var.setString(1, string);
var.executeQuery();
但是,它没有编译,出现以下错误。任何人都可以解释为什么我会收到这些错误吗?
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();
答案 0 :(得分:3)
这是因为prepareStatement
被声明为throw异常。
try {
PreparedStatement prepStmt = con.prepareStatement(mySql);
var.setString(1, string);
var.executeQuery();
}catch(SQLException ex){
//deal with exception
}
或者你可以使你的方法执行这个代码抛出一个例外:
public void myMethod() throws SQLException {
...
...
PreparedStatement prepStmt = con.prepareStatement(mySql);
var.setString(1, string);
var.executeQuery();
...
...
}
这是java中最基本的异常处理。您可以参考here了解更多信息
答案 1 :(得分:-1)
试试:
SELECT * FROM table WHERE column LIKE = ?;
然后,将String设置为: var.setString(1,“%”+ string +“%”);
它应该可以正常工作。