0

How want to fetch row data with variable name and print the values with index using with QSqlQueryModel. Below is my example code:

from PyQt5 import QtSql
import sqlite3

db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("users.db")

if db.open():
    query = QtSql.QSqlQuery()
    query.exec_("""CREATE TABLE IF NOT EXISTS user_name(name TEXT, age TEXT, mobile TEXT, mail TEXT)""")

model = QtSql.QSqlTableModel()
model.setTable("user_name")
model.select()

query.exec_("INSERT into user_name VALUES ('name1', 29, 123, 'Mail1.com')")
query.exec_("INSERT into user_name VALUES ('name2', 30, 456, 'Mail2.com')")
query.exec_("INSERT into user_name VALUES ('name3', 31, 789, 'Mail3.com')")

search = "name2"

conn = sqlite3.connect('users.db')
cur = conn.cursor()
select_query = "SELECT * FROM user_name WHERE name = ?"
cur.execute(select_query, (search_name,))
a = cur.fetchone()
print(a)
print(a[1])
cur.close()
result is:

('name1', '29', '123', 'Mail1.com')
123
Mail1.com

I am able to do this with Sqlite3 using with "WHERE" clause as above code. But i want to do this with QSqlQuery, QSqlTableModel.

How to Do this?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Mano
  • 27
  • 6

1 Answers1

0

You might want to try

conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row # This row makes the retrival dict
cur = conn.cursor()
select_query = "SELECT * FROM user_name WHERE name = ?"
cur.execute(select_query, (search_name,))
a = cur.fetchone()
print(a['name'])
cur.close()

Now you should be able to: print(a['name'])

Adam
  • 1,231
  • 1
  • 13
  • 37
  • Thank you for your response, but i want to try this using with QSqlQuery, QSqlTableModel. Is it possible. – Mano Oct 02 '20 at 12:16