带preparedstatement的Java查询,与insert一起使用,与select不一起使用
当我将preparedstatement与INSERT语句一起使用时,一切正常 当我将其用于SELECT语句时,会出现以下错误:带preparedstatement的Java查询,与insert一起使用,与select不一起使用,java,mysql,database,jdbc,driver,Java,Mysql,Database,Jdbc,Driver,当我将preparedstatement与INSERT语句一起使用时,一切正常 当我将其用于SELECT语句时,会出现以下错误: com.mysql.jdbc.StatementImpl cannot be cast to com.mysql.jdbc.PreparedStatement 在我开始在这里发帖之前,我做了研究。这个世界应该是这样的,我还将这个来源与我在互联网上找到的不同例子进行了比较 private Connection connection = null; private Pr
com.mysql.jdbc.StatementImpl cannot be cast to com.mysql.jdbc.PreparedStatement
在我开始在这里发帖之前,我做了研究。这个世界应该是这样的,我还将这个来源与我在互联网上找到的不同例子进行了比较
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;
}
数据库连接由构造函数处理,这很好。这不是问题。我不知道通过将
Connection.prepareStatement()
的结果强制转换到com.mysql.jdbc.PreparedStatement
来实现什么,但这是不必要的,实际上是问题的原因
您永远不应该依赖于任何特定于MySQL的类。你应该在接口上编程java.sql.PreparedStatement
,它是由Connection.prepareStatement()
返回的类型,具有使用PreparedStatement所需的一切
删除强制转换,并从代码(包括导入)中删除对MySQL类的任何引用。您已经完成了吗??真奇怪。也许是进口产品出了问题?尝试导入java.sql.PreparedStatement?尝试execute()而不是executeQuery()。谢谢,它很管用,你能解释一下为什么我不应该使用mysql引用吗?首先,因为你不需要它,因为你需要的所有方法都在标准Java接口中。其次,因为拥有这个对所有数据库驱动程序都通用的接口的全部意义在于能够在不依赖专有方法的情况下对所有数据库使用公共代码,并且能够在不必更改代码的情况下更改数据库。