標籤: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。。)