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;
}
* 取得相对路径的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;
}