JDBC–建立資料庫連接

來源:互聯網
上載者:User

 

 

 

JDBC建立資料庫連接時關於資料庫的使用者名稱,密碼,以及串連URL可以放在一個獨立檔案中。例如:

屬性檔案放在目錄 /test 中,它的內容是:

  1. drivers=com.microsoft.jdbc.sqlserver.SQLServerDriver
  2. url=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=studentmanager
  3. user=sa 
  4. password=wang411dong516

串連資料庫測試檔案DBConnection.java:

 

  1. /** 
  2. * 通過屬性檔案載入資料庫驅動程式,建立資料庫的串連 
  3. */ 
  4. import java.sql.SQLException; 
  5. import java.sql.Connection; 
  6. import java.sql.DriverManager; 
  7. import java.util.Properties; 
  8. import java.io.FileInputStream; 
  9. import java.io.IOException; 
  10. import java.io.FileNotFoundException; 
  11. public class DBConnection 
  12.     private String url;//資料庫URL  
  13.     private String userName;//登入資料庫使用者名稱  
  14.     private String password;//使用者密碼  
  15.     /** 
  16.      * 返回到資料庫的一個串連,在一個系統或類中,如果經常進行資料庫的相關操作 
  17.      * 會把建立資料庫的串連作為一個單獨的方法。 
  18.      */ 
  19.     public Connection getConnection() 
  20.     { 
  21.         getProperty(); 
  22.         Connection con = null; 
  23.         try 
  24.         { 
  25.             con = DriverManager.getConnection(url, userName, password); 
  26.         } 
  27.         catch(SQLException e) 
  28.         { 
  29.             e.printStackTrace(); 
  30.         } 
  31.         return con; 
  32.     } 
  33.     /** 
  34.      * 讀取屬性設定檔 
  35.      */ 
  36.     private void getProperty() 
  37.     { 
  38.         Properties prop = new Properties(); 
  39.         try 
  40.         { 
  41.             FileInputStream in = new FileInputStream("Driver.properties"); 
  42.             prop.load(in); 
  43.             String driver = prop.getProperty("drivers"); 
  44.             if(driver != null) 
  45.                 System.setProperty("jdbc.drivers", driver); 
  46.             url = prop.getProperty("url"); 
  47.             userName = prop.getProperty("user"); 
  48.             password = prop.getProperty("password");            
  49.         } 
  50.         catch(FileNotFoundException e) 
  51.         { 
  52.             e.printStackTrace(); 
  53.         } 
  54.         catch(IOException e) 
  55.         { 
  56.             e.printStackTrace(); 
  57.         } 
  58.     } 
  59. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.