PDA

View Full Version : SQLQuery assigning column



nethanjavier
26th July 2012, 08:09
Hi,
Here's my code. Is this right?

def sqlquery():
query = QSqlQuery(db)
query.prepare("Select itemcode, description, srp, vat from items Where itemcode=:itemcode;");
if query.next():
itemcode = query.value(0).toInt()
description = query.value(1).toString()
srp = query.value(2).toInt()
vat = query.value(3).toInt()
query.bindvalue(":itemcode", QtCore.QVariant(itemcode))
query.exec_()
return True

wysota
26th July 2012, 08:14
No, it's wrong.

nethanjavier
26th July 2012, 08:19
Man,your so fast. :-) What's the right way? Can you enlighten me? Thank you again wysota.

wysota
26th July 2012, 08:25
Currently you are trying to read data from the query before the query is made. You need to reorder your statements.

nethanjavier
26th July 2012, 08:41
def sqlquery():
query = QSqlQuery(db)
query.prepare("Select itemcode, description, srp, vat from items Where itemcode=:itemcode;");
query.exec_()
if query.next():
itemcode = query.value(0).toInt()
description = query.value(1).toString()
srp = query.value(2).toInt()
vat = query.value(3).toInt()
query.bindvalue(":itemcode", QtCore.QVariant(itemcode))
return True

How about this? Is this right now wysota?

wysota
26th July 2012, 08:45
No. Do you understand what value() and bindValue() do? Did you read the fine docs on QSqlQuery? There are examples of doing queries there.

nethanjavier
26th July 2012, 09:01
Man, from what I've read in that documentation, value is a field from my table. So using this code: itemcode = query.value(0).toInt() is wrong? Can you teach me the right way? I already read many documentations and examples, but man, I still can't get it.

wysota
26th July 2012, 09:06
So using this code: itemcode = query.value(0).toInt() is wrong?
If you issue that call before the query is executed then what do you expect to receive in "itemcode"?
Furthermore if you call bindValue() after you execute the query then what do you expect the value of ":itemcode" to be used in the query?
If your query doesn't return any rows then what exactly do you expect your variables to contain?

nethanjavier
30th July 2012, 02:53
Man, that's how far I understand in PyQt. Using that code,I'm expecting a value that i could pass to my tableview. As what I have explained before, I want to put the values(itemcode,description,srp and vat) to my tableview if my lineedit will find any value in my items table in my database. By using that bindvalue, I could query to my table or finding a record to my table. If my query doesn't find any record, I want to show and error message. Hope you understand me wysota.