I wanted to load SQLite database from disk to memory and I'm using JDBC driver, but I couldn't find any proper method in Java to do this.
JDBC Driver:
implementation group: 'org.xerial', name: 'sqlite-jdbc', version: '3.36.0.3'
I found that here, In python we can use below code to do that
import sqlite3
source = sqlite3.connect('existing_db.db')
dest = sqlite3.connect(':memory:')
source.backup(dest)
Is there any similar approach in Java also ?
Update - 1
I tried using restore command but even that didn't work
Connection connection =
DriverManager.getConnection("jdbc:sqlite:file:prod?mode=memory&cache=shared", config.toProperties());
Statement statement = connection.createStatement();
statement.executeUpdate("restore from products.db");
Update - 2
(In response to Answer by @Sergey Vyacheslavovich Brunov)
I'm attaching the code I used and it's output. If we see the Non-Heap Memory(Native Memory) usage there is no much increase, but also I was able to print the number of entries loaded (Output Section).
Now where are records getting loaded? Not able to track it
package com.example.sqlite.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.sqlite.SQLiteConfig;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
@Service
@Slf4j
public class CacheService {
private static Connection globalConnection = null;
public static Connection getConnection() {
return globalConnection;
}
public String buildCache() {
try {
SQLiteConfig config = new SQLiteConfig();
config.setPragma(SQLiteConfig.Pragma.JOURNAL_MODE, "wal");
config.setPragma(SQLiteConfig.Pragma.SYNCHRONOUS, "normal");
config.setPragma(SQLiteConfig.Pragma.TEMP_STORE, "memory");
globalConnection = DriverManager.getConnection("jdbc:sqlite:file::memory:?cache=shared",
config.toProperties());
try (
Connection connection = DriverManager.getConnection(
"jdbc:sqlite:file::memory:?cache=shared", config.toProperties());
Statement statement = connection.createStatement()
) {
statement.executeUpdate("restore from /Users/swastikn/Desktop/products.db");
ResultSet resultSet =
statement.executeQuery("SELECT COUNT(*) AS count FROM products_1");
log.info("Successfully loaded {} entries into Memory", resultSet.getInt("count"));
resultSet.close();
return "SUCCESS";
}
} catch (Exception e) {
log.error("Error while building cache: {}", e.getMessage());
}
return "ERROR";
}
}
Output
2022-07-09 13:23:10.741 INFO 2591 --- [nio-8081-exec-1] com.example.sqlite.service.CacheService : Successfully loaded 584524 entries into Memory