Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite (JDBC) not writing data

Tags:

java

sqlite

jdbc

I have got an application which reads and writes data to a sqlite database. In some situations I have to write some data, and read this data as soon as it is in the DB. See example below.

    public void read() throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:sqlite:C:\\test.sqlite");
    c.setAutoCommit(false);
    try {
        PreparedStatement p = c.prepareStatement("SELECT * FROM test");
        try {
            ResultSet rs = p.executeQuery();
            try {
                while (rs.next()) {
                    System.out.println(rs.getInt("val"));
                }
            } finally {
                rs.close();
            }
        } finally {
            p.close();
        }
    } finally {
        c.close();
    }
}

public void write() throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:sqlite:C:\\test.sqlite");
    c.setAutoCommit(false);
    try {
        PreparedStatement p = c.prepareStatement("INSERT INTO test (val) VALUES (?)");
        try {
            p.setDouble(1, Math.random());
            p.executeUpdate();
            c.commit();
        } finally {
            p.close();
        }

    } finally {
        c.close();
    }
}

public void demonstrate() {
    write();
    read();
}

If I call the demonstrate method, the data gets written without any exceptions, but the read method outputs nothing on stdout. If I restart the application, I am able to see the data which was written within the last run. The example shown above is simplified. In the real application there's much more data per query to be written.

So why does SQLite not see the data written in the current session?

like image 218
gorootde Avatar asked Sep 08 '25 13:09

gorootde


1 Answers

I noticed you are using the Driver Manager to get a SQLConnection. You probably forgot to register the SQL Driver in the Driver Manager. You should have something like this somewhere in your code (you just need to do it once):

  DriverManager.registerDriver(new org.sqlite.JDBC());

EDIT:

You have a small bug in your code: you are writing doubles and reading ints. To test I have created a table "test" with a column "val" of type double.

In every time I run the program, a new line is written in the output:

0
0
0

This is the output after running the program 3 times. The database has 3 rows, and every time i run the program one more is added (the 0 values are because you are reading ints from a double value, and random returns a value between 0 and 1).

The only explanation I have is probably a bug in your SQLite driver.

See my Answer here for a driver update

like image 78
Filipe Palrinhas Avatar answered Sep 10 '25 07:09

Filipe Palrinhas