createStatement()方法如何返回Statement的对象?

时间:2013-12-13 20:50:38

标签: java jdbc interface

根据javadoc,createStatement()方法创建了一个Statement实例,用于将SQL语句发送到数据库。

现在Statementinterface下的java.sql包,我的理解是无法用Java创建接口实例。

然后它是如何工作的? 在源头我发现了这一点,只有我不明白。

/**
 * Creates a <code>Statement</code> object for sending
 * SQL statements to the database.
 * SQL statements without parameters are normally
 * executed using <code>Statement</code> objects. If the same SQL statement
 * is executed many times, it may be more efficient to use a
 * <code>PreparedStatement</code> object.
 * <P>
 * Result sets created using the returned <code>Statement</code>
 * object will by default be type <code>TYPE_FORWARD_ONLY</code>
 * and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
 * The holdability of the created result sets can be determined by
 * calling {@link #getHoldability}.
 *
 * @return a new default <code>Statement</code> object
 * @exception SQLException if a database access error occurs
 * or this method is called on a closed connection
 */
Statement createStatement() throws SQLException;

3 个答案:

答案 0 :(得分:4)

它需要一个JDBC驱动程序才能工作。 JDBC驱动程序实现java.sql中描述的接口。驱动程序的Connection实现有一个createStatement方法的实现,它返回驱动程序的Statement实现。

JDBC是让供应商提供他们自己的特定于供应商的JDBC实现,同时为用户提供统一的界面。数据库提供JDBC驱动程序,驱动程序实现接口:如果查看jar驱动程序的jar文件,您将看到许多特定于供应商的类,如:

WhateverRdbmsConnectionImpl
WhateverRdbmsPreparedStatementImpl
...

等,其中每个实现java.sql接口。

所以你可能会看到

public class WhateverRdbmsConnectionImpl implements java.sql.Connection {

    public java.sql.Statement createStatement() throws java.sql.SQLException {
        WhateverRdbmsStatementImpl stmt = new WhateverRdbmsStatementImpl();
        ...
        return stmt;
    }
}

createStatement需要返回实现接口java.sql.Statement的内容,供应商提供自己的实现。

答案 1 :(得分:2)

以下是一些示例代码:

interface IBlammy
{
    public String blam();
}

class BlammyImpl
implements IBlammy
{
    public String blam()
    {
        return "kapow";
    }
}


class Hooty
{
    public IBlammy getStatement()
    {
        return new BlammyImpl();
    }
}

Hooty.getStatement()返回对实现IBlammy接口的对象的引用。

答案 2 :(得分:2)

您正在查看Connection界面的来源,而不是。接口不包含任何类型的实现 - 它们只是定义一个契约,实现该接口的类必然会实现该接口上的所有内容。

http://docs.oracle.com/javase/7/docs/api/java/sql/Connection.html