1

I have a problem passing a variable like

query7 = QSqlQuery ("SELECT Exemplo FROM TabelaSubst WHERE Palavra="+text+" ORDER BY Exemple ASC;")

Im getting anything passing my variable text like this. and if i do print query7.next() im getting false..

my program is with PYQT , i have a combobox, when i select some text from it, i pass this text to my variable "text", and i want to use it in my Where Palavra = text, but i dont know how to do it. Im doing it because with it i will get examples of these texts and im putting it in a qtablewidget..

when i do a search with a word, like

query7 = QSqlQuery ("SELECT Exemplo FROM TabelaSubst WHERE Palavra='ronaldo' ORDER BY Exemple ASC;")

.. its ok.. i get my table with examples... But if i change "ronaldo" for my variable text, i get anything..

The way im creating the table to put the examples is:

index1 = 0

while (query7.next()):
        self.tableWidget.setItem(index1,0,QTableWidgetItem(query7.value(0).toString()))  
        index1 = index1+1
Marco
  • 339
  • 2
  • 11
  • 20

1 Answers1

1

Either wrap text in quotes, or put quotes into your query string. For example:

text = "'%s'" % text

or

query7 = QSqlQuery ("SELECT Exemplo FROM TabelaSubst WHERE Palavra='"+text+"' ORDER BY Exemple ASC;")
Brent Washburne
  • 12,904
  • 4
  • 60
  • 82
  • 1
    Both of these methods leave your app open to SQL injection. – Blender Aug 19 '13 at 18:23
  • That's true, I just noticed that `text` comes from a combo box. It should be cleaned up before being passed to the query. – Brent Washburne Aug 19 '13 at 18:26
  • i still getting false when i do print query7.next() with your query7 = QSqlQuery ("SELECT Exemplo FROM TabelaSubst WHERE Palavra='"+text+"' ORDER BY Exemple ASC;") But if i change "+text+" for ronaldo and print query7.next() it returns true – Marco Aug 19 '13 at 18:28
  • and the "text" is from my db. I first open some text from my db into combobox then i want to make a search about this word, taking examples about it and using it in my qtablewidget – Marco Aug 19 '13 at 18:32
  • You can debug your program by printing values as they are created. Put your query string into a temporary variable and print it out so you can see exactly what it looks like. Then print out the value of `query7`, and so on. – Brent Washburne Aug 19 '13 at 18:33
  • Well, doing query7 = QSqlQuery ("SELECT Exemplo FROM TabelaSubst WHEREPalavra='"+text+"';") return true and its ok. I will search about this problem with ORDER BY. Thanks. – Marco Aug 19 '13 at 18:43