2012-03-15 87 views
3

我无法访问服务器上的数据库。我正在使用代码片段来尝试连接。使用相对路径定位(连接到)数据库时遇到困难

String currentDir = new File(".").getAbsolutePath(); 
String currdir = System.getProperty("user.dir"); 
System.out.println("EPIC currentDir = " + currentDir); 
System.out.println("EPIC currdir = " + currdir); 
String builder = "jdbc:sqlite:"+ currentDir +"dbname"; 

现在..的printlns告诉我说:

currentDir = /usr/local/cpanel/base/. 
currdir = /usr/local/cpanel/base 

,我知道这是怎么回事,因为我的数据库位于 给的SQLException ../WEB-INF/lib/ DBNAME 所以毫不奇怪,我收到此错误信息:

java.sql.SQLException: opening db: '/usr/local/cpanel/base/.dbname': Permission denied 

所以我的问题是这样的..什么是基地后如何,涉及到我的目录(从哪里servl et运行)?我没有SSH去寻找它(卷眼睛),如果任何人都可以阐明这个问题,我会很高兴! 在此先感谢!

编辑:怪异的东西

我测试这一切都与这些命令..

String currentDir = new File("dbname").getAbsolutePath(); 
String currdir = System.getProperty("user.dir"); 
System.out.println("EPIC currentDir = " + currentDir); 
System.out.println("EPIC currdir = " + currdir); 
System.out.println("EPICER = " + this.getClass().getResource("dbname").toString()); 
System.out.println("EPICEST! = "); 

这是输出:

EPIC currentDir = /usr/local/cpanel/base/dbname 

< <这个人给我的“权限被拒绝“

EPIC currdir = /usr/local/cpanel/base 

< <这个人给我的 “权限被拒绝”

EPICEST! = 

< <这是确定..但等待..没有EPICER ???

System.out.println("EPICER = " + this.getClass().getResource("dbname").toString()); 

不打印!什么?是我的日志被过滤,以防止我查看路径?此外,没有这些路径的工作:(

< < < < --- UPDATE --- >>>>

没有打印,因为“这个”被返回null和我其实是在这个越来越NPE 。线;因此,没有任何的println咄

最后编辑时间: 解决

好了,我要去一下都错了,我张贴这以防其他一些可怜的家伙大约是浪费!像我这样做了三天..

this.getClass().getResource("dbname").toString()) 

“这个”是因为什么而返回null的?意外的是,没有ServletContext的 所以

getServletContext() 

也返回null(这是我与后来的实验)

我从其他资源学的互联网络,我打算这样做这样的方式是完全错误的,因为,我每次重新部署WAR文件,数据库将被覆盖。所以我在我的/ home /用户名/被叫DBFILES创建一个小的目录和使用的命令:

String dir= "jdbc:sqlite:/home/username/dbfiles/dbname.db"; 
connection = DriverManager.getConnection(dir); 

和它的作品!

谢谢大家

+1

错误说:“访问被拒绝”,所以我不认为有什么问题与路径。 – 2012-03-15 08:55:42

+0

[如何从Web档案的WEB-INF目录加载资源]的可能重复(http://stackoverflow.com/questions/1108434/howto-load-a-resource-from-web-inf-directory-of- a-web-archive) – Snicolas 2012-03-15 08:57:53

+0

aah,所以它找到数据库但没有读/写权限? – tricknology 2012-03-15 08:58:09

回答

1

user.dir来是系统用户的目录。 如果你想找到你的应用程序的战争里面的文件,然后使用ServletContext.getRealPath()

+0

ServletContext返回null,因为我是一个noob ..我也不需要使用tomcat7和web.xml(从我可以看到我的不注意眼睛)。但是,我确实发现了将web.xml放入其/ WEB-INF /中的人员的实例。为什么?它有什么作用?如果你有任何资源可以像我一样为n00bs拼出来,请分享。此外,我解决了这个问题,它在最后的编辑。 – tricknology 2012-03-15 11:35:57

0

要使用JDBC从一个Applet访问数据库(只读):

我发到这里列出http://www.shoaibinamdar.in/blog/?p=313了一个类似的连接,但的

ds.setUrl("jdbc:sqlite::resource:"+ 
    getClass().getResource("sample.db").toString()); 

insread我把

ds.setUrl("jdbc:sqlite:resource/sample.db"); 

在sample.db去/ myprojectname/resourc E/sample.db,在同一个目录(myprojectname)为/ myprojectname/src目录资源是/

希望这可以帮助别人