How to give a relative path in Java for database

限于喜欢 提交于 2019-12-13 05:54:46

问题


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


回答1:


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



回答2:


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:


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.



来源:https://stackoverflow.com/questions/15998802/how-to-give-a-relative-path-in-java-for-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!