Hi,
I have met some problems when I opened the same database file twice in
the same process.

#include <stdio.h>
#include <stdlib.h>

#include <glib.h>
#include <sqlite3.h>

int main (int argc, char * argv[])
{
sqlite3 * db1 = NULL;
sqlite3 * db2 = NULL;
sqlite3_stmt * pstmt = NULL;
gchar * errorstr = NULL;
gint ret;
gint test_num = 100;

if (sqlite3_open("./test.db", &db1))
{
g_print("%s(): %s\n", __FUNCTION__, sqlite3_errmsg(db1));

return EXIT_FAILURE;
}

if (sqlite3_open("./test.db", &db2))
{
g_print("%s(): %s\n", __FUNCTION__, sqlite3_errmsg(db2));

return EXIT_FAILURE;
}


if (sqlite3_exec(db1, "CREATE TABLE IF NOT EXISTS test1 ( tid1 INTEGER
PRIMARY KEY, tid2 INTEGER );", NULL, NULL, &errorstr) != SQLITE_OK)
{
g_print("%s(): %s\n", __FUNCTION__, errorstr);
g_free(errorstr);

return EXIT_FAILURE;
}

if (sqlite3_exec(db2, "CREATE TABLE IF NOT EXISTS test2 ( tid1 INTEGER
PRIMARY KEY, tid2 INTEGER );", NULL, NULL, &errorstr) != SQLITE_OK)
{
g_print("%s(): %s\n", __FUNCTION__, errorstr);
g_free(errorstr);

return EXIT_FAILURE;
}

/*
* if I close the databases here, and then reopen them,
* the following steps wil run correctly with no errors.
*/

ret = sqlite3_prepare(db1, "INSERT INTO test1 ( tid1, tid2 ) values (
:1, :2 );", -1, &pstmt, 0);
if (ret != SQLITE_OK)
{
g_print("%s(): %s\n", sqlite3_errmsg(db1));

return EXIT_FAILURE;
}

sqlite3_bind_int(pstmt, 1, test_num);
sqlite3_bind_int(pstmt, 2, test_num);

ret = sqlite3_step(pstmt);
if (ret != SQLITE_DONE)
{
g_print("%s(): insert into test 1, WARNING %s.\n", __FUNCTION__,
sqlite3_errmsg(db1));

return EXIT_FAILURE;
}

ret = sqlite3_finalize(pstmt);

ret = sqlite3_prepare(db2, "INSERT INTO test2 ( tid1, tid2 ) values (
:1, :2 );", -1, &pstmt, 0);
if (ret != SQLITE_OK)
{
g_print("%s(): %s\n", sqlite3_errmsg(db2));

return EXIT_FAILURE;
}

sqlite3_bind_int(pstmt, 1, test_num);
sqlite3_bind_int(pstmt, 2, test_num);

ret = sqlite3_step(pstmt);
if (ret != SQLITE_DONE)
{
g_print("%s(): insert into test 2, WARNING %s.\n", __FUNCTION__,
sqlite3_errmsg(db2));

return EXIT_FAILURE;
}

ret = sqlite3_finalize(pstmt);

sqlite3_close(db1);
sqlite3_close(db2);

return EXIT_SUCCESS;
}
As the detils showed in the above codes, I opened the database files
twice in the same process but with two different sqlite3 handler db1 and
db2. And then I created two different talbes with these two handlers
seperately. The problem is that when I want to inert some data into two
tables with two different database handlers db1 and db2, a common
warning ocurred: SQL error or missing database. This error happend
randomly when the insert to table 1 or the insert to table 2 and
sometimes the data will be insert corretle and sometimes not.
Just now, I found this error will NOT happen definitely if I close the
database after I have created the tables and reopen it before I insert
data to it.

Is there some important step I missed or any other solution for this
problem?

Regards,
Nan Ye



Reply via email to