JDBC註冊驅動程序3種方式

以MySQL的驅動爲例,介紹註冊驅動程序的3種方式java

1:Class.forName("com.mysql.cj.jdbc.Driver");// 加載數據庫驅動mysql

 1 package com.pine.interview.jdbc;  2 
 3 import java.sql.Connection;  4 import java.sql.DriverManager;  5 import java.sql.SQLException;  6 
 7 public class Driver1 {  8     public static void main(String[] args) throws ClassNotFoundException, SQLException {  9         Class.forName("com.mysql.cj.jdbc.Driver");// 加載數據庫驅動
10         String url = "jdbc:mysql://localhost:3306/pine?serverTimezone=UTC";// 數據庫鏈接子協議
11         Connection conn = DriverManager.getConnection(url, "root", "root"); 12  System.out.println(conn); 13  conn.close(); 14  } 15 }

2:System.setProperty("jdbc.drivers","com.mysql.cj.jdbc.Driver");// 加載數據庫驅動sql

 1 package com.pine.interview.jdbc;  2 
 3 import java.sql.Connection;  4 import java.sql.DriverManager;  5 import java.sql.SQLException;  6 
 7 public class Driver2 {  8     public static void main(String[] args) throws ClassNotFoundException, SQLException {  9         System.setProperty("jdbc.drivers","com.mysql.cj.jdbc.Driver");// 加載數據庫驅動
10         String url = "jdbc:mysql://localhost:3306/pine?serverTimezone=UTC";// 數據庫鏈接子協議
11         Connection conn = DriverManager.getConnection(url, "root", "root"); 12  System.out.println(conn); 13  conn.close(); 14         /**
15  * 能夠同時導入多個jdbc驅動,中間用冒號「:」分開 16  好比System.setProperty("jdbc.drivers","XXXDriver:XXXDriver:XXXDriver"); 17          */
18  } 19 }

3:new com.mysql.cj.jdbc.Driver();// 加載數據庫驅動數據庫

 1 package com.pine.interview.jdbc;  2 
 3 import java.sql.Connection;  4 import java.sql.DriverManager;  5 import java.sql.SQLException;  6 
 7 public class Driver3 {  8     public static void main(String[] args) throws SQLException {  9         new com.mysql.cj.jdbc.Driver();// 加載數據庫驅動
10         String url = "jdbc:mysql://localhost:3306/pine?serverTimezone=UTC";// 數據庫鏈接子協議
11         Connection conn = DriverManager.getConnection(url, "root", "root"); 12  System.out.println(conn); 13  conn.close(); 14  } 15 }

推薦使用方法一、方法2,其中方法2能夠一次性註冊多個驅動url

不推薦使用方法3,由於編譯時會依賴mysql的驅動包,並且靜態代碼塊中會進行驅動的註冊,new 出來的 Driver的實例是多餘無用的spa

以下圖所示:code

相關文章
相關標籤/搜索