[SOLVED]Getting string from QSql query
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()))
query = QSqlQuery()
query.exec_('SELECT name FROM cases WHERE id =:id)')
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.
query.prepare("SELECT name FROM cases WHERE id =:id)");
The idea: I think it's better to prepare query first and then bind values.
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:
TypeError: QSqlQuery.exec(str): not enough arguments@
If I put the underscore after exec I get:
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:
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);
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:
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.@