我正在经历一个很大的疑问。今天练习数据库连接以及从MySQL数据库的表中读取记录。一切正常。
在编码时,我遇到了两个接口(interface),一个是连接,第二个是语句。 使用以下代码片段设置连接后。
Connection Con = DriverManager.getConnection(host, username, password);
我必须创建一个用于执行 SQL 查询的 Statement 对象。所以我就这样做了,并且能够获得记录。
Statement stmnt = Con.createStatement();
String SQL = "SELECT * FROM sys_config";
ResultSet rs = stmnt.executeQuery( SQL );
我的问题是,如果大多数时候都需要Statement对象,那么为什么在Connection
接口(interface)中声明createStatement()
。为什么不在Statement接口(interface)下声明呢?有什么我真的不知道的具体原因吗?
最后,下面的代码用于获取对由 StatementImpl
实现的对象的 Statement
引用。
public class ConnectionImpl
extends ConnectionPropertiesImpl
implements Connection
{...
public Statement createStatement()
throws SQLException
{
return createStatement(1003, 1007);
}
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException
{
checkClosed();
StatementImpl stmt = new StatementImpl(this, this.database);
stmt.setResultSetType(resultSetType);
stmt.setResultSetConcurrency(resultSetConcurrency);
return stmt;
}
}
最佳答案
createStatement()
方法不是静态的。它依赖于Connection
数据。如果方法在 Statement 接口(interface)中创建为静态,则需要请求 Connection 实例作为输入参数。
不同的Connection
实现可能会以不同的方式(并使用不同的实现)实例化Statements
。
因此决定将实例化作为Connection
责任的一部分。
关于java - 为什么createStatement方法是在Connection接口(interface)而不是Statement接口(interface)下声明的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45661964/