12

I want to read a SQLite db file using Java. Will you please tell me how to read it?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Priya
  • 121
  • 1
  • 1
  • 3

2 Answers2

10

First read these answers

David Crawshaw developed a JAR file (still available on github here but not touched for 10+ years). Taro Saito has a self-contained straightforward JAR file available on github here that includes the JDBC driver and the native runtimes required. Just add this JAR file to your classpath and import java.sql.*

David's test app will create a database file, send some SQL commands to create a table, store some data in the table, and read it back and display on console. It will create the test.db file in the root directory of the project.

public class Test {
    public static void main(String[] args) throws Exception {
        Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
        Statement stat = conn.createStatement();
        stat.executeUpdate("drop table if exists people;");
        stat.executeUpdate("create table people (name, occupation);");
        PreparedStatement prep = conn.prepareStatement(
            "insert into people values (?, ?);");

        prep.setString(1, "Gandhi");
        prep.setString(2, "politics");
        prep.addBatch();
        prep.setString(1, "Turing");
        prep.setString(2, "computers");
        prep.addBatch();
        prep.setString(1, "Wittgenstein");
        prep.setString(2, "smartypants");
        prep.addBatch();

        conn.setAutoCommit(false);
        prep.executeBatch();
        conn.setAutoCommit(true);

        ResultSet rs = stat.executeQuery("select * from people;");
        while (rs.next()) {
            System.out.println("name = " + rs.getString("name"));
            System.out.println("job = " + rs.getString("occupation"));
        }
        rs.close();
        conn.close();
    }
  }
MartinMlima
  • 1,736
  • 1
  • 12
  • 13
ayush
  • 14,350
  • 11
  • 53
  • 100
  • 1
    unLuckly, the link is not found now, try this: https://github.com/xerial/sqlite-jdbc – Eddy Oct 22 '15 at 12:52
3

The Java JDBC driver for SQLLite is on the David Crawshaw site http://www.zentus.com/sqlitejdbc/ Add the jar file to your class path and import java.sql.* and you should be good.

Piyush Mattoo
  • 15,454
  • 6
  • 47
  • 56