Sandy
Sandy

Reputation: 1053

access "in memory" database from other thread

I have created an in memory database using the statement:

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

I need to access this database in other thread (for reading data). Is there any way to access this in memory database in other thread?

The documentation says:

Every :memory: database is distinct from every other. So, opening two database connections each with the filename :memory: will create two independent in-memory databases.

If I create multiple in memory database, how can I access these databases from other thread?

Upvotes: 2

Views: 1048

Answers (1)

user610650
user610650

Reputation:

The db variable in your code becomes the pointer to the SQLite db object created:

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

Ref.: http://www.sqlite.org/capi3ref.html#sqlite3_open

This is the pointer you will use in your different threads to execute statements. For example, you prepare statements with the following function to which you'll pass your db pointer:

int sqlite3_prepare(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);

Ref.: http://www.sqlite.org/c3ref/prepare.html

EDIT:

I don't know if you can change the name of the memory database that you open with sqlite3_open(":memory:", ...), but it does have a name. Also you can attach additional in-memory databases.

There is a good chance that the initially opened in-memory database name is main. You can verify that by running the statement pragma database_list.

You can attach more in-memory database by running statements such as ATTACH DATABASE ':memory:' AS db2;.

Here is a quick demo of the above using the sqlite3 client:

[someone@somewhere ~]$ sqlite3
SQLite version 3.7.7.1 2011-06-28 17:39:05
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .headers on
sqlite> pragma database_list;
seq|name|file
0|main|
sqlite> attach database ':memory:' AS db2;
sqlite> pragma database_list;
seq|name|file
0|main|
2|db2|
sqlite> create table main.foo (bar int);
sqlite> create table db2.foo (bar int);
sqlite> insert into main.foo values (5);
sqlite> insert into db2.foo select * from main.foo;
sqlite> select * from db2.foo;
bar
5

Upvotes: 2

Related Questions