简体   繁体   中英

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.

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). If you can't do that either, the proper handler is 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.

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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