Swa*_*wag 0 java mysql database jdbc driver
当我使用带有INSERT语句的preparestatement时,一切正常.
当我将它用于SELECT语句时,我收到此错误:
com.mysql.jdbc.StatementImpl cannot be cast to com.mysql.jdbc.PreparedStatement
Run Code Online (Sandbox Code Playgroud)
在我开始发布之前,我做过研究.这应该是世界,我也将这个来源与我在互联网上找到的不同例子进行了比较.
private Connection connection = null;
private PreparedStatement statement = null;
private ResultSet result = null;
public boolean usernameAvailable(String username) throws SQLException{
boolean available = true;
String query = "SELECT Username FROM User WHERE Username = ?";
try{
statement = (PreparedStatement) connection.prepareStatement(query);
statement.setString(1, username);
result = statement.executeQuery();
while(result.next()){
available = false;
}
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
finally{
if(statement != null){ statement.close(); }
if(connection != null){ connection.close(); }
}
return available;
}
Run Code Online (Sandbox Code Playgroud)
数据库连接由构造函数处理,并且工作正常.那不是问题.
我不知道你想铸造的结果,要达到什么Connection.prepareStatement()来com.mysql.jdbc.PreparedStatement,但是这是不必要的,实际上是你的问题的原因.
你永远不应该依赖任何MySQL特定的类.你应该在接口上编程.java.sql.PreparedStatement,返回的类型Connection.prepareStatement(),具有使用预准备语句所需的一切.
删除强制转换,并从代码中删除对MySQL类的任何引用(包括导入).