jdbc为什么(正如java文档所说)我们不能从PreparedStatement或CallableStatement调用语句接口中的execute方法?
java文档中语句接口中的所有execute-type方法中都有一个注释:
Note:This method cannot be called on a PreparedStatement or CallableStatement.
但为什么会这样呢?我的意思是PreparedStatement
是Statement
的子接口,那么为什么我们不能这样做呢?事实上,我试过了,而且成功了
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 楼答案
它工作的事实意味着您使用的驱动程序实现(我猜是MySQL Connector/J)不符合JDBC 4.1(或更高版本)规范。JDBC API javadoc不仅面向API用户,还描述了驱动程序供应商需要实现的行为
各种
execute(String)
,executeQuery(String)
等的API文档说:JDBC 4.1(Java 7)中添加了这个粗体部分,以澄清预期的行为
这有几个原因:
execute...(String)
方法会忽略准备好的语句,因此您调用此方法可能是一个错误。提出一个例外说明你做错了什么李>execute...(String)
并随后尝试使用execute...()
执行时出现意外行为,并期望它使用之前的prepared语句李>事后看来
Statement
、PreparedStatement
和CallableStatement
形成继承层次结构可能是一个错误。为了向后兼容,这一点不能再更改