简体   繁体   English

如何在Java中为数据库提供相对路径

[英]How to give a relative path in Java for database

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. 我想问一下如何在java中为数据库提供相对路径(ms访问),这样当我将项目放在其他驱动器中时,就不必编辑路径部分了。

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: 但是,如果我将项目更改到另一个文件夹,请假设d:,则必须像下面这样编辑此路径部分:

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 我想给出一个相对路径,以便我的项目可以在任何带有该\\ project \\ a.mdb的驱动器上运行

Well,this is what we called parameterize ! 好吧,这就是我们所谓的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

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. 但是解决该问题的一种方法是允许将路径配置为启动命令行参数,env变量或系统属性。

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. 您还可以确保数据库在类路径中,并通过使用getResource找到数据库的位置,该方法将为您提供数据库的URL。 This can then be used to translate it into a file path. 然后可以将其转换为文件路径。

AFAIK, if you leave off the drive name part of a pathname, a Windows application will look on the "current" drive. AFAIK,如果省略了路径名的驱动器名称部分,则Windows应用程序将在“当前”驱动器上查找。

So try changing the pathname you are using from "d:\\\\project\\\\a.mdb" to "\\\\project\\\\a.mdb" . 因此,尝试将您使用的路径名从"d:\\\\project\\\\a.mdb"更改为"\\\\project\\\\a.mdb"

Note however that this will mean that you need to set the current drive before launching your application; 但是请注意,这将意味着您需要在启动应用程序之前设置当前驱动器。 eg type D: or C: at the command prompt. 例如,在命令提示符下键入D:C: :。


A better alternative would be to make the database path a command line parameter or an entry in a property file or something. 更好的选择是使数据库路径成为命令行参数或属性文件中的条目或其他内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM