日期:2014-05-16 浏览次数:20591 次
第一次,没调用getProperties()方法,代码如下:
package util; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; public class DBUtil { private static String driverClassName; private static String url; private static String username; private static String password; public static Properties ps = new Properties(); public static void getProperties() throws IOException{ InputStream ips= DBUtil.class.getClassLoader() .getResourceAsStream("db.properties"); ps.load(ips); driverClassName = ps.getProperty("driverClassName"); url = ps.getProperty("url"); username = ps.getProperty("username"); password = ps.getProperty("password"); } public static Connection getConnection() throws Exception{ /*//配置文件方式*/ getProperties(); //这里没有调用,导致获取不到参数值,纠结了半小时才调试出来 Class.forName(driverClassName); Connection conn = DriverManager.getConnection(url,username,password); return conn; } public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
====DAOFactory.java文件的代码==== public class DAOFactory { DBUtil.getConnection();//这里没有调用,导致获取不到参数值,纠结了2个小时,且不能在 DBUtil.getValue(type)前直接先调用 String className = DBUtil.getValue(type); //一直获取不到className的值 ... } ====DBUtil.java文件的代码==== public class DBUtil { private static String driverClassName; private static String url; private static String username; private static String password; public static Properties ps = new Properties(); public static void getProperties() throws IOException{ InputStream ips= DBUtil.class.getClassLoader() .getResourceAsStream("daoconfig.properties"); ps.load(ips); driverClassName = ps.getProperty("driverClassName"); url = ps.getProperty("url"); username = ps.getProperty("username"); password = ps.getProperty("password"); } public static Connection getConnection() throws Exception{ /*//配置文件方式*/ getProperties(); Class.forName(driverClassName); Connection conn = DriverManager.getConnection(url,username,password); return conn; } public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } /*根据参数key,获取配置文件的参数值value*/ public static String getValue(String key){ return ps.getProperty(key); } /*调试*/ public static void main(String[] args) throws Exception{