@Test
public void fun() throws ClassNotFoundException, SQLException
{
/*
* jdbc 四大配置參數:
* >driverClassName:com.mysql.jdbc.Driver
* >url: jdbc:mysql://localhost:3306/數據庫名
* >用戶名
* >密碼
*/
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/mydb3";
String username="root";
String password="123";
Connection con=DriverManager.getConnection(url,username,password);
System.out.println(con);
}
這是常規java程序連接數據庫的流程。
當程序運行到 Class.forName(“com.mysql.jdbc.Driver”); 時,類加載器加載了com.mysql.jdbc.Driver這個類,通過找尋該類的源代碼
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
發現該類有如上的靜態代碼塊,在該類加載時,會執行靜態代碼塊的內容,因此代碼也有相當於如下代碼
@Test
public void fun() throws ClassNotFoundException, SQLException
{
/*
* jdbc 四大配置參數:
* >driverClassName:com.mysql.jdbc.Driver
* >url: jdbc:mysql://localhost:3306/數據庫名
* >用戶名
* >密碼
*/
com.mysql.jdbc.Driver driver=new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
String url="jdbc:mysql://localhost:3306/mydb3";
String username="root";
String password="123";
Connection con=DriverManager.getConnection(url,username,password);
System.out.println(con);
}
這樣就將這兩行代碼的關係聯串起來。