【发布时间】:2013-11-21 22:14:38
【问题描述】:
当我将preparedstatement 与INSERT 语句一起使用时,一切正常。
当我将它用于 SELECT 语句时,我收到此错误:
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;
}
数据库连接由构造函数处理,工作正常。这不是问题。
【问题讨论】:
-
确实很奇怪。也许进口有问题?尝试导入 java.sql.PreparedStatement; ?
-
尝试 execute() 而不是 executeQuery()
标签: java mysql database jdbc driver