#include "mainwindow.h" #include "./ui_mainwindow.h" #include #include #include #include #include MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); qDebug() << QSqlDatabase::drivers(); // this configuration is assuming the Windows SQL server is running in the local host QSqlDatabase db = QSqlDatabase::addDatabase("QODBC"); db.setHostName("localhost"); db.setDatabaseName("localhost-test"); // the name of the data source configured in ODBC Data sources db.setUserName("USER"); // your username on the local host (Windows) db.setPassword("PASSWORD"); // password for the user bool ok = db.open(); if (ok) { qDebug() << "Connected to SQL Server successfully"; /* ---------- */ QSqlQuery q(db); #define TEMPORARY (1) // set 1 to use a temporary table #if (TEMPORARY) #define TABLENAME "#tmpTable" #else #define TABLENAME "tmpTable" #endif qDebug() << "starting preparing 1st query"; #if (1) QString query1 = QString("CREATE TABLE [") + TABLENAME + "](id int NOT NULL)"; q.prepare(query1); qDebug() << "executing 1st query"; bool b = q.exec(); // returns true #else bool b = q.exec(query); // this gets along with the following operations #endif qDebug() << "starting preparing 2nd query"; QString query2 = QString("INSERT INTO [") + TABLENAME + "](id) VALUES(?)"; q.prepare(query2); QVariantList l; for (int i = 0; i < 10; i++) l << i; q.addBindValue(l); qDebug() << "executing 2nd query"; q.execBatch(); // this returns false and throws an error when a temporary table used qDebug() << "starting preparing 3rd query"; QString query3 = QString("SELECT * FROM [") + TABLENAME + "]"; q.prepare(query3); qDebug() << "executing 3rd query"; q.exec(); // this returns false and throws an error when a temporary table used while (q.next()) qDebug() << q.record().value(0).toString(); #if (!TEMPORARY) QString query4 = QString("DROP TABLE ") + TABLENAME; q.prepare(query4); qDebug() << "executing 4th query"; q.exec(); #endif /* ---------- */ db.close(); } else { qDebug() << "Error connecting to SQL Server:" << db.lastError().text(); } } MainWindow::~MainWindow() { delete ui; }