用於與資料庫連接的JDBC和驅動程式的理解,資料庫連接jdbc

來源:互聯網
上載者:User

用於與資料庫連接的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     }

 輸出:

資料庫連接成功

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.