java调用properties配置文件连接数据库

    用配置文件连接数据库

1. Eclipse中,在src目录下建立db.properties文件,在里面配置数据库连接所需的      Driver,url,user,possword ,注意等号左右不能空格
 如:

driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;databaseName=restrant
user=root
password=110


2.写一个数据库连接类

ConnDB类
package tools;
import java.sql.*;
public class ConnDB {

	  public Connection conn = null;
	  public Statement stmt = null;
	  public ResultSet rs = null;
	  public ConnDB(){ }
	  /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
	  public static Connection getConnection() {
		
		  PropertiesUtils.loadFile("/db.properties");
		  String url = PropertiesUtils.getPropertyValue("url");
		  String user = PropertiesUtils.getPropertyValue("user");
		  String password = PropertiesUtils.getPropertyValue("password");
		  String driver = PropertiesUtils.getPropertyValue("driver");
		  		  
	    Connection conn = null;
	    try {
	      Class.forName(driver);	      
	      conn = DriverManager.getConnection(url,user,password);
	    }
	    catch (Exception ee) {
	      ee.printStackTrace();
	    }
	    if (conn == null) {
	      System.err.println("error~~~~~~~~~~~~~~~" );
	    }
	    return conn;
	  }



PropertiesUtils 类 供读取db.properties 配置文件
package tools;

import java.io.IOException; 
import java.util.Properties; 
public class PropertiesUtils { 
//产生一个操作配置文件的对象 
static Properties prop = new Properties(); 
/**
* @param fileName 需要加载的properties文件,文件需要放在src根目录下 
* 是否加载成功 
*/ 
public static boolean loadFile(String fileName){ 
  try { 
prop.load(PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName)); 
} catch (IOException e) { 
e.printStackTrace(); 
return false; 
} 
return true;
} 
/** 
* 根据KEY取回相应的value 

*/
public static String getPropertyValue(String key){ 
return prop.getProperty(key); 
} 
} 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值