日期:2014-05-16  浏览次数:20486 次

java通过配置属性文件连接Oracle数据库
???? 做web项目开发中,通过配置属性文件实现连接数据库(Oracle)的功能。
???1.将属性文件放在WEB-INF/classes目录下
???? 例如属性文件:demo_db.properties
???? DRIVERS=oracle.jdbc.driver.OracleDriver
???? URL=jdbc:oracle:thin:@localhost:1521:MyOra
???? USER=user
??? ?PASSWORD=123456
???2.写一个连接数据库的类
??? 例如:DBUtils.java
  1. package?com.ctcjz.db;
  2. import?java.sql.Connection;
  3. import?java.sql.DriverManager;
  4. import?java.sql.ResultSet;
  5. import?java.sql.SQLException;
  6. import?java.sql.Statement;
  7. import?java.util.ResourceBundle;
  8. public?class?DBUtils?{
  9. ????private?static?final?String?OPTION_FILE_NAME?=?"demo_db";
  10. ????private?static?String?drivers;
  11. ????private?static?String?url;
  12. ????private?static?String?user;
  13. ????private?static?String?password;
  14. ????static?{
  15. ????????ResourceBundle?res?=?ResourceBundle.getBundle(OPTION_FILE_NAME);
  16. ????????drivers?=?res.getString("DRIVERS").trim();
  17. ????????url?=?res.getString("URL").trim();
  18. ????????user?=?res.getString("USER").trim();
  19. ????????password?=?res.getString("PASSWORD").trim();
  20. ????}
  21. ????public?static?Connection?getConnection()?throws?SQLException?{
  22. ????????Connection?conn?=?null;
  23. ????????try?{
  24. ????????????Class.forName(drivers).newInstance();
  25. ????????????conn?=?DriverManager.getConnection(url,?user,?password);
  26. ????????}?catch?(Exception?e)?{
  27. ????????????e.printStackTrace();
  28. ????????}
  29. ????????if?(conn?==?null)?{
  30. ????????????throw?new?SQLEx