有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jdbc为什么(正如java文档所说)我们不能从PreparedStatement或CallableStatement调用语句接口中的execute方法?

java文档中语句接口中的所有execute-type方法中都有一个注释:

Note:This method cannot be called on a PreparedStatement or CallableStatement.

但为什么会这样呢?我的意思是PreparedStatementStatement的子接口,那么为什么我们不能这样做呢?事实上,我试过了,而且成功了

    ConnectionSetup setCon = new ConnectionSetup();
    // My own class for increasing readability.
    try{

        setCon.loadDriver("com.mysql.jdbc.Driver");//loadDriver calls Class.forName.
        con = setCon.setUpConnection("jdbc:mysql://localhost:3306/odi batsman", "root", "");//setUpConnection asks DriverManager for Connection Object.
        PreparedStatement ps = con.prepareStatement(query);
        ps.execute(query);
    }
    catch(ClassNotFoundException | SQLException e){

        e.printStackTrace();
    }

它工作得非常好,尽管我从PreparedStatement调用了execute方法(它以字符串作为输入,并从接口Statement继承),但记录还是成功地输入到了数据库中。怎么回事

EDIT我只是想问,它是用java文档编写的,我们不能从PreparedStatement调用execute(string),但因为它是Statement的子接口,为什么我们不能呢


共 (1) 个答案

  1. # 1 楼答案

    它工作的事实意味着您使用的驱动程序实现(我猜是MySQL Connector/J)不符合JDBC 4.1(或更高版本)规范。JDBC API javadoc不仅面向API用户,还描述了驱动程序供应商需要实现的行为

    各种execute(String)executeQuery(String)等的API文档说:

    SQLException - if a database access error occurs, this method is called on a closed Statement, the method is called on a PreparedStatement or CallableStatement

    JDBC 4.1(Java 7)中添加了这个粗体部分,以澄清预期的行为

    这有几个原因:

    1. 调用其中一个execute...(String)方法会忽略准备好的语句,因此您调用此方法可能是一个错误。提出一个例外说明你做错了什么
    2. 在某些数据库系统上,在语句句柄上执行除prepared语句之外的语句字符串可能会使prepared语句无效,从而导致在首次使用execute...(String)并随后尝试使用execute...()执行时出现意外行为,并期望它使用之前的prepared语句

    事后看来StatementPreparedStatementCallableStatement形成继承层次结构可能是一个错误。为了向后兼容,这一点不能再更改