Java and SQLite [closed] Java and SQLite [closed] sqlite sqlite

Java and SQLite [closed]


I found your question while searching for information with SQLite and Java. Just thought I'd add my answer which I also posted on my blog.

I have been coding in Java for a while now. I have also known about SQLite but never used it… Well I have used it through other applications but never in an app that I coded. So I needed it for a project this week and it's so simple use!

I found a Java JDBC driver for SQLite. Just add the JAR file to your classpath and import java.sql.*

His 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. You can run this example with java -cp .:sqlitejdbc-v056.jar Test.

package com.rungeek.sqlite;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;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();    }  }


The wiki lists some more wrappers:


I understand you asked specifically about SQLite, but maybe HSQL database would be a better fit with Java. It is written in Java itself, runs in the JVM, supports in-memory tables etc. and all that features make it quite usable for prototyping and unit-testing.