Search code examples
c++qtsqliteqsqlqueryqsqldatabase

How to lock a table in a database via Qt?


I have connected to a database in Qt using c++.

 QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
 db.setDatabaseName("/link/to/my.db");

Simultaneously I have a Python program that connect to same database and constantly updates a table called "myTable".

From Qt I want to read the newly updated rows each time I poll. So I want to

Lock the table; Read all rows; Delete all the rows; Unlock the Table.

How do I lock and Unlock the table in Qt


Solution

  • There is no lock command for tables in SQLite. But you can lock the database by transaction :

    BEGIN IMMEDIATE TRANSACTION;
    ...
    COMMIT TRANSACTION;
    

    Or

    BEGIN EXCLUSIVE TRANSACTION;
    ...
    COMMIT TRANSACTION;
    

    So you can execute transactions commands before and after your operations :

    q.exec("BEGIN IMMEDIATE  TRANSACTION");
    
    ...
    
    q.exec("COMMIT");
    

    Or

     db.transaction(); // Begins a transaction
    
     ...
    
     db.commit(); //Commits a transaction