SQLite Forum

database keep locked by a function in C++

database keep locked by a function in C++

(1) By Luca (HakimLaxe) on 2020-11-20 18:43:18 [link] [source]

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:

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);

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:

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);

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

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

} In main:

int main(){

if ( find_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.

(2) By Richard Hipp (drh) on 2020-11-20 20:19:45 in reply to 1 [source]

You need to invoke sqlite3_finalize() on the prepared statement when you are finished using it, before the function returns.