The code really is about as simple as already shown above. Here is another example (that sends raw SQL from a text box to a database, executes the command, and then displays the results in a table)
https://github.com/pitonyak/ADPStampInventory/blob/master/sqldialog.cpp[
^]
The relevant code is in the first couple lines are shown below. The example above is better for most cases, however, because it uses bind values, but, the example below assumes it is in a particular environment where the DBA type person enters a SQL command and it is executed so no bind values.
void SQLDialog::executeSql(const QString& sqlString)
{
QSqlDatabase& db = m_db.getDB();
QSqlQuery query(db);
if (!query.exec(sqlString))
{
m_statusBar->showMessage(query.lastError().text());
}
else
{
if (query.isSelect())
{
if (m_tableWidget == nullptr)
{
m_statusBar->showMessage(tr("Select not displayed because table widget is null"));
}
else
{
QSqlRecord rec = query.record();
int numCols = rec.count();
int numRows = query.size() + 1;
m_tableWidget->clear();
m_tableWidget->setColumnCount(numCols);
m_tableWidget->setRowCount(numRows);
QStringList fieldNames;
int i;
for (i=0; i<rec.count(); ++i)
{
fieldNames << rec.fieldName(i);
}
m_tableWidget->setHorizontalHeaderLabels(fieldNames);
int row=0;
while (query.isActive() && query.next())
{
for (int col=0; col<numCols; ++col)
{
QTableWidgetItem *newItem = new QTableWidgetItem(query.value(col).toString());
if (numRows <= row)
{
numRows = row + 1;
m_tableWidget->setRowCount(numRows);
}
m_tableWidget->setItem(row, col, newItem);
}
++row;
}
m_tableWidget->resizeColumnsToContents();
m_statusBar->showMessage(QString(tr("Read %1 records")).arg(row));
}
}
else
{
int numAffected = query.numRowsAffected();
if (numAffected >= 0)
{
m_statusBar->showMessage(QString(tr("Successful query with %1 rows arrected")).arg(numAffected));
}
else
{
m_statusBar->showMessage(QString(tr("Successful query!")));
}
}
}