JDBC连接数据库无法获取db.properties原因

/**
 * @author Administrator
 * 管理连接工具
 */
public class DBTool {
    private  static String url;
    private  static String user;
    private  static String pwd;
    
    //静态块在加载类时执行一次
    static{
        //加载连接参数
        Properties p =new Properties();
        //使用ClassLoader 读取类路径下(classpath/src) 下的文件,得到一个输入流
        InputStream is=DBTool.class.getClassLoader().getResourceAsStream("util/db.properties");
        System.out.println("读取成功");
        try {
            //从流中读取数据
            p.load(is);
            //从p(散列表)中获取4个连接参数
            String driver =p.getProperty("driver");
            System.out.println("获取成功1");
            url=p.getProperty("url");
            user=p.getProperty("user");
            pwd=p.getProperty("pwd");
            System.out.println("获取成功2");
            Class.forName(driver);
            System.out.println("获取成功3");
        } catch (Exception e) {
            
        }
        
        
    }
    
    /**
     * 创建连接
     */
    public static Connection getConnection() {
        try {
            return DriverManager
                .getConnection(url,user,pwd);
            
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(
                "创建连接失败", e);
        }
    }

    /**
     * 关闭连接
     * @param con 被关闭的连接
     * @param smt 被关闭的Statement
     */
    public static void close(
        Connection con, Statement smt) {
        try {
            if(smt != null) {
                smt.close();
            }
            if(con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(
                "释放资源失败", e);
        }
    }

    public static void main(String[] args) {
        Connection con =
            DBTool.getConnection();
        System.out.println(con);
        DBTool.close(con, null);
    }

}
写的工具类在连接数据库时抛出异常,无法获取db.properties文件,相关配置文件都正确。经过检查是发现获取不来db.properties的相关路径错误。D:\Users\Workspaces\ MyEclipse 10\OrJDBC01\src\util\db.properties 红色地方多了一个空格导致错误。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值