Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use SQLite to open a database from memory?

Tags:

c

sqlite

It looks like all the methods for loading SQLite involve loading from a named file using a string. I would like to load SQlite database from memory.

The database is already loaded into memory.

like image 285
Klathzazt Avatar asked Nov 10 '08 10:11

Klathzazt


People also ask

Does SQLite load entire database into memory?

No, Sqlite will read data for hard disk by paging. The Sqlite document said: "In order to return data from the database to the user, for example as the results of a SELECT query, SQLite must at some point read data from the database file.

Is SQLite in memory?

A SQLite in-memory database's primary advantage is performance: rather than reading and writing to disk, it will keep the whole database in memory. Memory is much faster than disk.

How do I run a SQLite database?

Start the sqlite3 program by typing "sqlite3" at the command prompt, optionally followed by the name the file that holds the SQLite database (or ZIP archive). If the named file does not exist, a new database file with the given name will be created automatically.


1 Answers

Use a special file name, :memory:

sqlite3_open(":memory:", &db);

libsqlite must have been compiled without SQLITE_OMIT_MEMORYDB defined, as pointed out in SQLite documentation:

SQLITE_OMIT_MEMORYDB

When this is defined, the library does not respect the special database name ":memory:" (normally used to create an in-memory database). If ":memory:" is passed to sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(), a file with this name will be opened or created.

If you want to read the database that is already fully loaded into memory however, it will be more work. You will have to implement a custom VFS layer to operate on memory files and register it with your SQLite context.

See:

  • sqlite3_vfs
  • sqlite3_io_methods

I have not implemented it myself, so I can't reliably tell whether you have to implement the entire new VFS layer, or you can get away with substituting some functions in the default one (latter is unlikely).

like image 140
Alex B Avatar answered Nov 09 '22 11:11

Alex B