I have built a quick app I’m trying to make to learn how I could implement dynamic fitment or category options list to a list of products(I.E. Make, Model, Year Search). I thought I found a simple way of doing this, but I have found it is harder than Ithought. I’ve made the combo boxes I need for the fitment options dynamicly but I can’t figure out how to take the ID for the fitment group and use it in a new query as part of the ‘where clause’. What is the best way in qt to use a variable as an int inside a query to a mssql db?
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtCore>
#include <QtGui>
#include <QtSql>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setHostName("ROBERT-PC");
db.setDatabaseName("mydsn32");
if(!db.open())
{
qDebug() << "Could Not Open";
}
else
{
QVBoxLayout *vbox = new QVBoxLayout();
qDebug() << "Open, and now closing";
QSqlQuery qry;
if(qry.exec("SELECT * FROM [BOBs].[dbo].[FitmentTagGroup]"))
{
qDebug() << "Query Was Opened";
while(qry.next())
{
QString combBoxName = qry.value(1).toString() + "CombBox";
int combBoxID = qry.value(0).toInt();
QLabel *combBoxNameLbl = new QLabel();
combBoxNameLbl->setText(combBoxName);
QComboBox *combBox = new QComboBox();
QSqlQuery qry2;
if(qry2.exec("SELECT * FROM [BOBs].[dbo].[FitmentTag] WHERE FitmentTagGroupID='1'"))
{
while(qry2.next())
{
qDebug() << qry2.value(2).toString();
}
}
else
{
qDebug() << "Query Could Not Open\n\t" << qry2.lastError();
}
vbox->addWidget(combBoxNameLbl);
vbox->addWidget(combBox);
}
}
else
{
qDebug() << "Query Could Not Open\n\t" << qry.lastError();
}
model = new QSqlQueryModel();
db.close();
QFrame *mainFrame = new QFrame();
mainFrame->setLayout(vbox);
setCentralWidget(mainFrame);
}
}
You should use prepared statements and binding values to solve your problem.
Instead of using
you should use something like this:
Read more here.