简体   繁体   English

Sqlite can't connect to database from inside jar: NullPointerException ClassNotFoundException: org.sqlite.JDBC

[英]Sqlite can't connect to database from inside jar: NullPointerException ClassNotFoundException: org.sqlite.JDBC

My connect code:我的连接代码:

private Connection connect(String dbpath)  {
        try  {
            Connection conn;
            Class.forName("org.sqlite.JDBC");

            conn = DriverManager.getConnection("jdbc:sqlite:" +
                    dbpath + ".db");
            System.out.println("Good!");
            return conn;
        }  catch (Exception e)  {
            System.out.println("Error!");
            return null;
        }
    }
dbpath = /home/username/stuff.db

It runs OK when I run from Idea Intellij, but when I package in jar it fails.当我从 Idea Intellij 运行时它运行正常,但是当我在 jar 中运行 package 时它失败了。

EDIT:编辑:

This is the error more down the stacktrace:这是堆栈跟踪中更多的错误:

ClassNotFoundException: org.sqlite.JDBC

 } catch (Exception e) { System.out.println("Error;"); return null; }

This is a 'doctor, it hurts when I smash this hammer in my face repeatedly' problem.这是一个“医生,当我反复用这把锤子砸我的脸时很痛”的问题。

Stop doing that.别那样做。

The proper way to handle an error is to handle it (logging it, isn't handling it).处理错误的正确方法是处理它(记录它,而不是处理它)。 The next best way is to throw the exception onwards (here, add throws SQLException to your method signature. It is entirely sensible for a method that is designed to connect to a DB, to do that).下一个最好的方法是继续抛出异常(在这里,将throws SQLException添加到您的方法签名中。对于旨在连接到数据库的方法来说,这样做是完全明智的)。 If you can't do that either, the proper handler is throw new RuntimeException("Uncaught", e);如果你也不能这样做,正确的处理程序是throw new RuntimeException("Uncaught", e); - because your way, well, leads to exceptions that no longer provide the information you need. - 因为你的方式,好吧,导致不再提供你需要的信息的例外。 You've tossed out all interesting parts.你扔掉了所有有趣的部分。 Most likely that db path isn't there (you are in a different directory), or possibly the CLass.forName call failed because your dependencies are broken.很可能该 db 路径不存在(您位于不同的目录中),或者 CLass.forName 调用失败,因为您的依赖关系已损坏。

Normally, the exception would tell you exactly which of these two cases is the problem.通常,异常会准确地告诉您这两种情况中的哪一种是问题所在。

But, because you wrote the snippet I showed above, now you don't.但是,因为你写了我上面展示的片段,现在你没有。 Thus, proving that snippet is bad.因此,证明该片段是不好的。 The solution is simple, though.不过,解决方案很简单。 Don't write code like that ever again:)不要再写那样的代码了:)

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

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