Java使用JDBC串連隨意類型資料庫(mysql oracle。。)

來源:互聯網
上載者:User

標籤:void   resource   string   driver   inf   pass   ack   oracle   ora   

package cn.liz.test;import java.io.InputStream;import java.sql.Connection;import java.sql.Driver;import java.sql.SQLException;import java.util.Properties;import org.junit.Test;public class JBDCtest {/** * 編寫一個通用的方法, 在不改動來源程式的情況下, 能夠擷取不論什麼資料庫的串連 * 解決方式: 把資料庫驅動 Driver 實作類別的全類名、url、user、password 放入一個 * 設定檔裡, 通過改動設定檔的方式實現和詳細的資料庫解耦.  * @throws Exception  */public  Connection getConnection() throws Exception{String driverClass = null;String jdbcUrl = null;String user = null;String password = null;//讀取類路徑下的 jdbc.properties 檔案InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");Properties properties = new Properties();properties.load(in);driverClass = properties.getProperty("driver");jdbcUrl = properties.getProperty("jdbcUrl");user = properties.getProperty("user");password = properties.getProperty("password");//通過反射常見 Driver 對象. Driver driver = (Driver) Class.forName(driverClass).newInstance();Properties info = new Properties();info.put("user", user);info.put("password", password);//通過 Driver 的 connect 方法擷取資料庫連接. Connection connection = driver.connect(jdbcUrl, info);return connection;}@Testpublic void testGetConnection() throws Exception{System.out.println(getConnection());}}<span style="white-space:pre"></span>
<span style="font-family: Arial, Helvetica, sans-serif;">jdbc.properties</span>設定檔:
#driver=oracle.jdbc.driver.OracleDriver#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl#user=scott#password=javadriver=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/testuser=rootpassword=

Java使用JDBC串連隨意類型資料庫(mysql oracle。。)

聯繫我們

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