Search code examples
javadatabasesqlitesqlexception

Java: Missing Database error


I am getting the following error:

java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: apartments)

In reality, the table does exist. The following is my code:

try {
    // load the sqlite-JDBC driver using the current class loader
    Class.forName("org.sqlite.JDBC");
    Connection connection = null;
    // create a database connection
    connection = DriverManager.getConnection("jdbc:sqlite:/Path/To/apartments.db");
    System.out.println(connection.getMetaData());
    Statement statement = connection.createStatement();
    statement.setQueryTimeout(30);

    ResultSet rs = statement.executeQuery("select * from apartments");
    while(rs.next()) {
        // read the result set
        System.out.println("TEXT = " + rs.getString("display_text"));
        System.out.println("X1 = " + rs.getInt("x1"));
    }
} catch (Exception ex) {
    Logger.getLogger(MouseEventDemo.class.getName()).log(Level.SEVERE, null, ex);
}

Solution

  • May be this can help you to get right path to you database

    How to Specify Database Files

    Here is an example to select a file C:\work\mydatabase.db (in Windows)

    Connection connection = DriverManager.getConnection("jdbc:sqlite:C:/work/mydatabase.db");
    

    A UNIX (Linux, Mac OS X, etc) file /home/leo/work/mydatabase.db

    Connection connection = DriverManager.getConnection("jdbc:sqlite:/home/leo/work/mydatabase.db");
    

    How to Use Memory Databases SQLite supports on-memory database management, which does not create any database files. To use a memory database in your Java code, get the database connection as follows:

    Connection connection = DriverManager.getConnection("jdbc:sqlite::memory:");
    

    This also can help

    String path=this.getClass().getResource("apartments.db").getPath();
                connection = DriverManager.getConnection("jdbc:sqlite:"+path);
    

    assumes that apartments.db is put in project root directory