JDBC 獲取連線的五種方式 MySql 8 0

2021-10-03 11:53:35 字數 1401 閱讀 6347

方式一:

public

void

test01()

throws sqlexception, classnotfoundexception

方式二:

不出現第三方的api 使用反射

public

void

test02()

throws sqlexception, exception

方式三: 使用drivermanager

public

void

test03()

throws sqlexception, exception

方式四:

簡化

//1.提供另外的三個連線資訊

string url=

"jdbc:mysql:"

; string user=

"root"

; string passwd=

"123456"

;//快捷鍵alt+上下可移動**

//2、獲取driver實現類物件 靜態**塊隨著類的載入而執行

class.

forname

("com.mysql.cj.jdbc.driver");

//這一步也是可省略的但只適用於mysql

//可以省略

//driver driver = (driver)clazz.getdeclaredconstructor().newinstance();

//註冊驅動

//為什麼可以省略

/* * 在mysql的driver實現類中,宣告了如下的操作:

* static catch (sqlexception e)

}會自動註冊驅動

*///3 獲取連線 alt+/

connection connection = drivermanager.

getconnection

(url,user,passwd)

; system.out.

println

(connection)

;}

方式五:將資料庫連線需要的4個基本資訊宣告在配置檔案中,通過讀取配置檔案的方式,獲取連線

此種方式的好處

JDBC資料庫連線的五種方式

方式一 通過driver驅動的connect string url,properties info 函式來建立連線,缺點出現了第三方資料庫的api new com.mysql.jdbc.driver test public void testconnection1 catch sqlexceptio...

jdbc獲取連線方式的改進

test public void testconnection1 throws sqlexception catch sqlexception e 方式一的不足 顯式出現了第三方資料庫的api 最好用到的都是sun公司自己的api test public void testconnection2 t...

JDBC獲取連線方式舉例 1

test public void testconnection1 catch sqlexception e 說明 上述 中顯式出現了第三方資料庫的api 連線方式二 test public void testconnection2 catch exception e 說明 相較於方式一,這裡使用反射...