Java读取属性文件链接oracle数据库

1、建立一个属性文件jdbc.propertiesjava

username =sql

password =数据库

url =jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST =)(PORT = )))(CONNECT_DATA=(SERVICE_NAME=)(SERVER=DEDICATED)))oracle

driverClassName =oracle.jdbc.driver.OracleDrivermaven

链接参数写本身要链接的数据库this

 

2、建立一个Java对象,字段是属性文件的各个属性参数url

package com.yolanda.fun.db; public class DataProperty { private String driverClassName; private String url; private String username; private String password; public String getDriverClassName() { return driverClassName; } public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } 


3、数据库链接类spa

package com.yolanda.fun.db; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; public class DbConnection { private String driverClassName; private String url; private String username; private String password; private Connection connection = null; public Connection connDb() { DataProperty dataProperty = getProperties(); this.driverClassName = dataProperty.getDriverClassName(); this.url = dataProperty.getUrl(); this.username = dataProperty.getUsername(); this.password = dataProperty.getPassword(); try { //反射oracle数据库驱动类 Class.forName(this.driverClassName); //获取数据库链接 this.connection = DriverManager.getConnection(this.url, this.username, this.password); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return this.connection; } public static void main(String[] args) { DbConnection dbConnection = new DbConnection(); dbConnection.connDb(); } /** * 获取数据库链接属性 * @return */ public DataProperty getProperties() { DataProperty dp = new DataProperty(); try { //从配置文件里读取数据库驱动,链接,用户名,密码 Properties properties = new Properties(); InputStream inputStream = DbConnection.class.getResourceAsStream("jdbc.properties"); properties.load(inputStream); dp.setDriverClassName("driverClassName"); dp.setPassword("password"); dp.setUrl("url"); dp.setUsername("username"); } catch (IOException e) { e.printStackTrace(); } return dp; } } 

4、pom文件里加个驱动.net

<dependency>code

  <groupId>oracle.jdbc</groupId>

  <artifactId>ojdbc14</artifactId>

  <version>10.2.0.5.0</version>

</dependency>

版本能够去本身的maven库里找个,没有的来这个下个

http://download.csdn.net/detail/yolanda_nuonuo/9641315