Search code examples
javaprogramming-languages

How to read an sqlite database file in Java? (Package)


Okay i know i have to use the JDBC etc, but im not sure how to implement the jar into my code, i have a basic code to open the file etc, but how can i actually incorporate the sqlite jar alongside my java class file to be run anywhere? So for example i have a folder with: Test.class new.db sqlite.jar

In Test.class i have the basic connection and imports:

Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;

    try {
        Class.forName("org.sqlite.JDBC");
        connection = DriverManager.getConnection("jdbc:sqlite:new.db");
        statement = connection.createStatement();
        resultSet = statement.executeQuery("SELECT empname FROM employee");
        while (resultSet.next()) {
            System.out.println("EMPLOYEE NAME:"
                    + resultSet.getString("empname"));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {  
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

So how can i have this simple little script portable? Thanks


Solution

  • Add the sqlite.jar to you classpath:

    java -cp .;./sqlite.jar Anima
    

    This should work. If not - please show your error message.


    Edit

    tested and verified. Create/Have a folder with the following content:

    ./project
        Anima.class
        sqlite.jar
    

    then cd to folder project and do a

    java -cp .;./sqlite.jar Anima
    

    It works as expected on my machine.