【问题标题】:Java query with preparedstatement, works with insert, not with select带有preparedstatement的Java查询,适用于插入,而不是选择
【发布时间】: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 mysql database jdbc driver


【解决方案1】:

我不知道你想通过将Connection.prepareStatement() 的结果转换为com.mysql.jdbc.PreparedStatement 来达到什么目的,但这是不必要的,实际上是你的问题的原因。

你不应该依赖任何 MySQL 特定的类。你应该在接口上编程。 java.sql.PreparedStatement,即Connection.prepareStatement()返回的类型,拥有使用prepared statement所需的一切。

删除强制转换,并从您的代码中删除对 MySQL 类的任何引用(包括导入)。

【讨论】:

  • 谢谢,它有效,你能解释一下为什么我不应该使用 mysql 引用吗?
  • 首先,因为您不需要它,因为您需要的所有方法都在标准Java接口中。其次,因为拥有所有数据库驱动程序通用的接口的全部意义在于能够在不依赖专有方法的情况下对所有数据库使用通用代码,并且能够在无需更改代码的情况下更改数据库.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
相关资源
最近更新 更多