我已經瞭解到Connection是一個接口,我們只能在接口中定義方法定義。 那麼,這如何工作:jdbc中的createStatement方法
....
語句stmt = con.createStatement();
....
該方法如何創建一個Statement對象並將其返回?
我已經瞭解到Connection是一個接口,我們只能在接口中定義方法定義。 那麼,這如何工作:jdbc中的createStatement方法
....
語句stmt = con.createStatement();
....
該方法如何創建一個Statement對象並將其返回?
因爲具體當您調用getConnection()
時,已執行Connection
接口。界面只是定義了方法簽名。具體實現包含方法實現。
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection.getClass().getName()); // That's the name of the concrete implementation.
這是包含那些具體實現的JDBC驅動程序。 JDBC API使您能夠獨立於所使用的特定數據庫服務器編寫Java代碼。無論何時切換數據庫,只需切換JDBC驅動程序(也可以在包含特定於DB服務器的SQL語言(而不是Java代碼)時更改SQL語句)。
看看這個例如。 這個概念與此類似。
public interface Human
{
public void run();
}
public class Man implements Human
{
public void run()
{
System.out.println("Man");
}
}
public class Main
{
public static void main(String s)
{
Human h= new Man();
h.run();
}
}
該程序的輸出爲Man
。
現在將它與您的問題進行比較。
Connection con = DriverManager.getConnection(url, username, password)
, con不指向連接對象,因爲它是一個接口,它指向一些已經明確繼承了Connection
接口的類。
現在,當你做到這一點
Statement stmt = con.createStatement();
它不叫Connection
接口方法,它調用CON實際refered方法。 所以你甚至不知道它會返回什麼東西,加上stmt肯定會指向哪個 繼承了Statement
接口。
你的意思是說它的數據庫特定類在Oracle的情況下執行像「oracle.jdbc.OracleDriver」這樣的實現。 – Ankit 2011-01-26 14:28:56