2013-12-13 73 views
2

根據javadoc,createStatement()方法會創建一個Statement實例來向數據庫發送SQL語句。createStatement()方法如何返回Statement對象?

現在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; 
+0

conn.createStatement()並不意味着有像「​​新聲明()」在該方法中存在的代碼。 – Loc

+4

createStatement返回對實現Statement接口的對象的引用。 – DwB

+2

相關:http://stackoverflow.com/questions/7550612/in-simplest-terms-what-is-a-factory/ – BalusC

回答

4

它需要一個JDBC驅動程序才能工作。 JDBC驅動程序實現java.sql中描述的接口。驅動程序的Connection實現具有createStatement方法的實現,該方法返回驅動程序的Statement實現。

JDBC是關於讓供應商提供他們自己的特定於供應商的JDBC實現,同時爲用戶提供統一的接口。數據庫提供JDBC驅動程序,驅動程序實現的接口:如果你找一個JDBC驅動程序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中,供應商提供他們自己的實現。

+0

沒有得到你的答案。 – Dhruv

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接口的對象的引用。