Java从入门到精通 - 数据库操作-相对路径的Connection

/**
  * 取得相对路径的Connection
  * @return
  */
 public static Connection getConnection(){
   Connection conn=null;
   try{
        String path="";
           Class theClass = ConnTest2.class;
           //System.out.println(ConnTest2.class.getResourceAsStream("db.mdb"));
           java.net.URL  u= theClass.getResource("db.mdb");  
           String ChinesePath = URLDecoder.decode(u.getPath().substring(1,u.getPath().length()).replaceAll("%20", " "),"UTF-8");
           //System.out.println(ChinesePath);
           String url="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+ChinesePath;
           Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
           //System.out.println("before connection");
           conn=DriverManager.getConnection(url);
      }catch(Exception ee){
        System.out.println("connect db error:"+ee.getMessage());
      }
      return conn;
    }

你可能感兴趣的:(java,数据库,exception,jdbc,String,Microsoft)