PDA

View Full Version : QSqlQuery problem



dragon
21st December 2006, 20:29
Hello anyone,

Iám newbe,

I have a mainWindow with a lineEdit called leFirst.
Ihave also a dialog called searchDialog with one combobox with 4 different names.(items)
When i call the dialog in my MainWindow en select one item on the combobox i want that item been search in my database and put the result to my lineEdit in my MainWindow.
code snippet:


void MainWindow::search()
{
searchDialog dlg(this);
if( dlg.exec() == QDialog::Accepted) {

QSqlQuery query("SELECT firstname FROM person");
QString name = dlg.nameComboBox->currentText();
if ( query.next() )
name = (query.value(0).toString());
leFirst->setText( name);
}
}

This works fine only for the first name in the combobox and showing up in the lineEdit.
When i choose for the second name in the combobox ( the second item) then in lineEdit only shows the first name again and not the second name.
Is something wrong in my code or missing something.
I have tried severall options but nothing works.

Thanks in advance.

wysota
21st December 2006, 21:51
Your code does not more, not less than:
1. Get "firstname" field from all records from the database
2. Store the text from the combobox in variable "name"
3. If there are any rows in the database...
a) assign the value of the first field in the first row of the query result to the variable "name"
b) set the contents of the line edit to the contents of the variable "name"

Bottom line:
You always set the value from the first row of the database regardless which item is selected in the combobox. You're not searching anything...

dragon
22nd December 2006, 06:42
I don't understand what you mean with assign en contents.
Can you give me a little example?.
Thank in advance.

wysota
22nd December 2006, 09:22
I don't understand what you mean with assign en contents.
Can you give me a little example?
Here you assign to the variable called name:

name = (query.value(0).toString());

If you want to make a search you need something like this:

while ( query.next() )
if(name == query.value(0).toString()){
leFirst->setText( name );
break;
}
}
Do you see the difference?

dragon
22nd December 2006, 17:04
Yes i see the differents.
It works fine.
Thak you for your time and answer.

wysota
22nd December 2006, 17:32
Of course it would be simpler to do it this way:


void MainWindow::search() {
searchDialog dlg(this);
if( dlg.exec() == QDialog::Accepted) {
QSqlQuery query;
query.prepare("SELECT firstname FROM person WHERE firstname==:name");
query.bindValue(":name", dlg.nameComboBox->currentText());
if(query.exec() && query.hasNext())
leFirst->setText( name);
}
}