0

Below is my example code:

db = QSqlDatabase.addDatabase('QSQLITE')
db.setDatabaseName('book.db')
db.open()

model = QSqlQueryModel()
model.setQuery("SELECT * FROM card")
self.tableView.setModel(model)

I am using QSqlQueryModel, Qtablevie, Sqlite3, and able to view all rows in my table. But i want to view only last two rows of my table which are newly inserted rows in to the table. The table has no "id" field and it has numaric and text fields. How is it possible? Below is the table image: enter image description here

user3030327
  • 411
  • 1
  • 7
  • 19

1 Answers1

2

If you want to get the last 2 elements ordered by any field that indicates the insertion order, in your case "rowid", then you have to use a filter in the SQL command like this:

model.setQuery("SELECT * FROM card ORDER BY rowid DESC LIMIT 2")

Another possible option is to filter the table using QSortFilterProxyModel but it is more inefficient.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • I added Above command but it is showing empty tableview. – user3030327 Aug 17 '20 at 07:10
  • @user3030327 I'm assuming that your table has a numeric "id" field, does it? You could indicate the fields of your table and what type they are. – eyllanesc Aug 17 '20 at 07:12
  • Actually it dose not has "id" field. and it have numeric and as well as text fields. If try with "rowid" It is working , can i use it . – user3030327 Aug 17 '20 at 07:18
  • Okay. I will edit my question that it has now "id" field. you can change the answer. Can i edit? – user3030327 Aug 17 '20 at 07:22
  • @user3030327 I don't understand you, the name "id" is irrelevant, it can be row_id, etc, logic is the most important. use `model.setQuery("SELECT * FROM card ORDER BY rowid DESC LIMIT 2")`. Analyze my answer and don't just do a copy-paste – eyllanesc Aug 17 '20 at 07:24
  • @user3030327 If you want more help then share your db as you don't seem to understand my answer – eyllanesc Aug 17 '20 at 07:29
  • This is working : `model.setQuery("SELECT * FROM card ORDER BY rowid DESC LIMIT 2")`. And this is not working `model.setQuery("SELECT * FROM card ORDER BY id DESC LIMIT 2")` which is in your answer. – user3030327 Aug 17 '20 at 07:34
  • @user3030327 mmm, I already adapted my answer to your particular case, are you happy already? The code provided should not be literal as the OP is expected to analyze what is justified and not just copy-paste machines. – eyllanesc Aug 17 '20 at 07:37
  • Actually i want to accept your answer that's why I edited my question and asked you to change your answer. :) – user3030327 Aug 17 '20 at 07:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/219964/discussion-between-user3030327-and-eyllanesc). – user3030327 Aug 17 '20 at 12:25