用於與資料庫連接的JDBC和驅動程式的理解,資料庫連接jdbc
理解:
java應用程式與資料庫建立串連時,先通過jdbc(jdbc是屬於jdk帶有的)與資料庫廠商提供的驅動程式通訊,而驅動程式再與資料庫通訊。
資料庫廠商提供的驅動程式:
資料庫的種類有多種,比如mysql、oracle等,不同的資料庫有不同的驅動程式。所以在進行其他動作前,首先要下載匯入對應的驅動程式jar包。
串連測試步驟:
先聲明所用到的資料庫的url、使用者名稱和密碼(資料庫的)
private static String url="jdbc:mysql://localhost:3306/mydb";private static String name="root";private static String password="1234";
1.載入驅動程式2.使用connect與資料庫建立串連
載入驅動程式有兩種方式:
1 public static void main(String[] args) { 2 try { 3 //載入驅動程式 4 Class.forName("com.mysql.jdbc.Driver"); 5 //使用connect與資料庫建立串連 6 Connection connection=(Connection) DriverManager.getConnection(url,name,password); 7 System.out.println("資料庫連接成功"); 8 } catch (Exception e) { 9 System.out.println("資料庫連接失敗");10 e.printStackTrace();11 }12 }
或者:
1 public static void main(String[] args) { 2 try { 3 //載入驅動程式 4 Driver driver=new Driver(); 5 DriverManager.registerDriver(driver);// 6 //使用connect與資料庫建立串連 7 Connection connection=(Connection) DriverManager.getConnection(url,name,password); 8 System.out.println("資料庫連接成功"); 9 } catch (Exception e) {10 System.out.println("資料庫連接失敗");11 e.printStackTrace();12 }13 }
輸出:
資料庫連接成功