[SOLVED]Getting string from QSql query
-
Hello again,
This time I'm having some trouble with QSql query, and extracting a string out of it. What I wanted to accomplish:
- There is QTableView object. When I click on a cell, it prints column and row numbers. (this is just a test, if it will work)
- I wanted to query the sqlite database, and extract a NAME where ID is ROW NUMBER.
@rownumber = index.row()
print ("Column is " + str(index.column()))
print ("Row is " + str(index.row()))
print (rownumber)
query = QSqlQuery()
query.bindValue(":id",rownumber)
query.exec_('SELECT name FROM cases WHERE id =:id)')
query.next()
tempname=str(query.value(0))
print (tempname)@After half-a-day worth of Googling this is the code I came up with, except it returns me this:
@Column is 1
Row is 7
QSqlQuery::value: not positioned on a valid record
None #this should be some NAME from database@Am I doing something wrong?
Thank you for reading.
-
-
Thank your for your reply,
I tried your code ( did you forget the underscore after exec? like exec_() ). When I execute the code you pasted I get:
@query.exec()
TypeError: QSqlQuery.exec(str): not enough arguments@If I put the underscore after exec I get:
@tempname=query.value(0).toString()
AttributeError: 'NoneType' object has no attribute 'toString'@Looks like the query got nothing? Query works like a charm from sqlite, it does return a value of column NAME at row 8
-
About underscore: probably I'm doing something wrong, but code I've posted was made from this:
@QSqlQuery query;
query.prepare("select * from goods where (model = :model) and (trademark = :trademark) and (country = :country)");
query.bindValue(":model", m_descriptor .m_model);
query.bindValue(":trademark", m_descriptor .m_trade_mark);
query.bindValue(":country", m_descriptor .m_country);
query.exec();@
And that code works.
About getting value. Actually I've never used this function. So I offer you to use QSqlQueryModel:
@
QSqlQueryModel *q_model = new QSqlQueryModel;
q_model ->setQuery (query);
@
Seems like this class gives more abilities to manipulate query results. -
Using QSqlQueryModel solved my problem.
Sample code which shows my solution:
@def clickedSlot(self,index):
rownumber = index.row()
colnumber = index.column()
self.model = QSqlQueryModel(self)self.model.setQuery("SELECT * FROM cases") tempname = self.model.data(self.model.index(rownumber, 1)) templastname = self.model.data(self.model.index(rownumber, 2)) fullname = tempname + ' '+ templastname print(fullname) #prints the result to the console.@