读取properties文件连接数据库

来源:互联网 发布:数据库学哪个 编辑:程序博客网 时间:2024/06/15 21:39

在properties文件中配置数据库的连接信息(数据库驱动driver、数据库url、用户名和密码),在java类中读取配置参数并连接数据库。

properties文件放在resoure目录下。

db.properties

[java] view plain copy
  1. driver=com.mysql.jdbc.Driver  
  2. url=jdbc:mysql://localhost/hibernate  
  3. username=root  
  4. password=123456  

编写一个读取properties属性文件的方法类PropertiesUtils

PropertiesUtils.java

[java] view plain copy
  1. package com.xuxu.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Properties;  
  5.   
  6. public class PropertiesUtils {  
  7.     static Properties property = new Properties();  
  8.     public static boolean loadFile(String fileName){   
  9.         try {  
  10.             property.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName));  
  11.         } catch (IOException e) {  
  12.             e.printStackTrace();  
  13.             return false;     
  14.         }     
  15.         return true;  
  16.     }  
  17.     public static String getPropertyValue(String key){     
  18.         return property.getProperty(key);  
  19.     }  
  20. }  

连接数据库的类DBUtil

DBUtil.java

[java] view plain copy
  1. package com.xuxu.util;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7. import java.sql.Statement;  
  8.   
  9. public class DBUtil {  
  10.     public Connection conn= null;  
  11.     public Statement stmt= null;  
  12.     public ResultSet rs= null;  
  13.       
  14.     public DBUtil(){}  
  15.       
  16.     public static Connection getConnection(){  
  17.         PropertiesUtils.loadFile("db.properties");  
  18.         String url = PropertiesUtils.getPropertyValue("url");  
  19.         String username = PropertiesUtils.getPropertyValue("username");  
  20.         String password = PropertiesUtils.getPropertyValue("password");    
  21.         String driver = PropertiesUtils.getPropertyValue("driver");    
  22.           
  23.         Connection conn = null;    
  24.         try {  
  25.             Class.forName(driver);  
  26.             conn = DriverManager.getConnection(url,username,password);  
  27.         } catch (ClassNotFoundException e) {  
  28.             e.printStackTrace();  
  29.         } catch (SQLException e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.         if(conn==null){  
  33.             System.out.println("error!!!!!");  
  34.         }  
  35.         return conn;  
  36.     }  
  37.       
  38.     public static void main(String[] args) {  
  39.         System.out.println(DBUtil.getConnection());  
  40.     }  
  41. }  
阅读全文
0 0
原创粉丝点击