I am painfully aware of the number of posts on this subject, but trawling through them hasn't helped me so far.
I have a maven project that uses a sqlite3 database. This runs successfully from within intelliJ. But I wanted to check that it was also capable of running as a jar by running this command:
Bradleys-MBP:general-state-machine atkinsb$ java -cp target/general-state-machine-1.0-SNAPSHOT.jar com.bradley.atkins.state.GeneralStateMachine
No suitable driver found for jdbc:sqlite:/Users/atkinsb/.general_state_machine/default/20171112105601/database/sm.db
Exception in thread "main" java.lang.ClassNotFoundException: org.sqlite.JDBC
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.bradley.atkins.state.StateMachineDb.executeSqlStatement(StateMachineDb.java:82)
at com.bradley.atkins.state.StateMachineDb.createTables(StateMachineDb.java:33)
at com.bradley.atkins.state.StateMachineInit.prepareDatabase(StateMachineInit.java:54)
at com.bradley.atkins.state.StateMachineInit.prepare(StateMachineInit.java:12)
at com.bradley.atkins.state.GeneralStateMachine.main(GeneralStateMachine.java:12)
I'm fairly inexperienced with Java and am struggling to understand why this fails. Possible answers that have come up while googling around are:
- I need to somehow include the sqlite3 jar itself into my project. Perhaps making this a "fat jar" instead of relying on maven pulling it in as a dependency?
- I need to add the sqlite3 jar to my class path in intelliJ. I don't know how to explicitly set this...
Explicitly load the jar from code like this:
Class.forName("org.sqlite.JDBC");
just prior to establishing a connection...
- I am trying to run the jar directly from the command line and need to set the path to sqlite3?
My maven setting for the dependency is:
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.20.1</version>
</dependency>
While my method looks like:
public static void executeSqlStatement(String sql) throws ClassNotFoundException {
Connection conn = null;
Class.forName("org.sqlite.JDBC");
try {
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
stmt.execute(sql);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
Like I said, this all works ok form within IntelliJ but am I going about confirming it will work as a standalone jar in the right way? I hope to eventually compile this project as a jar that other projects can pull in as an import.
Any advice on how to ensure I can get to that point would be much appreciated.
Thanks
Bradley