sqlite3: database keep locked by a function

I made a simple C++ program with sqlite3, it's composed by several function in which in each function I open the database at the begin, and i close it ad the end. I didn't realize why, but I'm sure, that there is a function that keep the database locked and don't allow other function to work propertly (I'm always able to read data from DB, but not to write on it by using UPDATE instruction in sql). The function that lock the database is this one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 bool find_user(const std::string& user) {


    sqlite3* db = database_open("UTENTE.db");
    sqlite3_stmt* statement;

    std::string query =
    "SELECT COUNT(*) FROM UTENTE WHERE Username = '"+ user + "';";

    sqlite3_prepare_v2(db, query.c_str(), -1, &statement, 0);
    sqlite3_step(statement);

    if (sqlite3_column_int(statement, 0) == 0) {
    
            std::cout << "User:" << user << "doesn't exist" << std::endl;
            return false;
        }
   
    return true;

    }

One of the functiones that modify DB:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void connect_user(const std::string& user) {

    sqlite3* db = database_open("UTENTE.db");


    char* err;
    std::string query = "UPDATE UTENTE SET Online=1 WHERE Username='" + user + "';";
    try {
        int res = sqlite3_exec(db, query.c_str(), NULL, NULL, &err);
        database_close(db);

        if (res != SQLITE_OK)
            std::cout << "Error during update: " << err << std::endl;
    }

    catch (std::exception& e)
    {
        std::cerr << "Exception: " << e.what() << "\n";
    }

}

In main:

1
2
3
4
5
6
7
 int main(){

    ....
    if ( find_user('JoeDoe') )
      connect_user('JoeDoe');
    ....
}


I get this output: Error during update: database table is locked: UTENTE The strange thing is that I'm using a simple singleThread application, so I shouldn't have any cuncurrency problem.
Last edited on
So why don't you add a database_close(db) to your find_user function?
Topic archived. No new replies allowed.