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

聯繫我們

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