how to give a relative path in java for databse, S

2019-08-22 04:28发布

I want ask how to give a relative path in java for a database(ms access) so that when I put my project in other drive then I don't have to edit the path section.

Given below is the absolute path for the database:

con=DriverManager.getConnection( "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};**DBQ=c:\\project\\a.mdb"** );

But if I change my project to another folder, suppose d: then I have to edit this path section like this:

con=DriverManager.getConnection( "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=**d:\\project\\a.mdb"** );

I want give a relative path so that my project will run on any drive with this \project\a.mdb

3条回答
Anthone
2楼-- · 2019-08-22 05:01

AFAIK, if you leave off the drive name part of a pathname, a Windows application will look on the "current" drive.

So try changing the pathname you are using from "d:\\project\\a.mdb" to "\\project\\a.mdb".

Note however that this will mean that you need to set the current drive before launching your application; e.g. type D: or C: at the command prompt.


A better alternative would be to make the database path a command line parameter or an entry in a property file or something.

查看更多
乱世女痞
3楼-- · 2019-08-22 05:06

I don't know how flexible the driver you're using is when it comes to using paths (never used that driver). But one way to solve it would be to allow the path to be configurable, either as a startup command line parameter, or as an env variable or system property.

You could also make sure that the database is in the classpath, and find it's location by using getResource which will give you an URL to the database. This can then be used to translate it into a file path.

查看更多
戒情不戒烟
4楼-- · 2019-08-22 05:08

Well,this is what we called parameterize! Just make the path as parameter,and passed it in on the runtime.Here is a demo:

public class DBOperation {
    public static void main(String[] args) {
     String path=args[0];
     String url="jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};**DBQ="+path+"**)";
     ...
    }
}

And run the programme by:

java DBOperation c:\project\a.mdb
查看更多
登录 后发表回答