vendredi 24 juin 2016

QODBC connects to SQL server but can not execute queries

Title says most of what's going on. I can confirm that I'm connecting to the database and I'm definitely opening the connection before I try to make a query. The problem is, every time I send the query through exec(query), I'm getting an error stating that my QODBC driver isn't loaded. If that's really the case then how am I even getting a connection to start with? And more importantly how do I re-write my code or configure something so that my drivers are being loaded?

Some things to fill in the gaps:

  • popupwindows.h is what is controlling AlertWindow, ErrorWindow, and Success Window and doesn't affect anything here at all.
  • I'm getting all the constants and data just fine, so it's nothing in how I'm putting together my SQL query, example:

INSERT INTO RegTable(Project_ID, Project_Name, Cycle, Number, B1, B2, B3, Horiz, Vert, Skew) VALUES (117.001, ZT400-300DPI, 0, 1, 1, 2, 3, 4, 5, 6)

  • I am getting true values for db.isOpen() and db.isValid() when I start the sendData() function, though I took them out once I ruled out errors with what they were checking.

  • I have qsqlodbc.dll and qsqlodbcd.dll in several folders throughout my application directory, but most importantly in

    C:pathtobuiltprojectdebugsqldrivers
    

Sorry for the wall-o-code but I wanted to make sure you all had everything you needed.

databaseconnection.cpp:

#include <QFile>
#include <QTextStream>
#include <QSqlError>
#include <QSqlQuery>
#include "databaseconnection.h"
#include "popupwindows.h"

DatabaseConnection::DatabaseConnection(QWidget *parent, QString type) {
    this->setParent(parent);
    log = new EventLog("DatabaseConnection");
    connected = false;
    db = QSqlDatabase::addDatabase("QODBC");        //note that this is a QString, not a QSqlDriver
    loadParams();
    connectDB(type);
}

DatabaseConnection::~DatabaseConnection() {
    db.close();
}

bool DatabaseConnection::connectDB( QString driverString) {
    if (!db.isOpen()) {
        if (db.isValid() && db.isDriverAvailable(driverString)) {
            QString connParams = QString("Driver={SQL SERVER};DSN=ODBCDriverForLocal;SERVER=" + server +";DATABASE="
                                     + database + ";Uid=" + username +";Pwd=" + password);
        db.setDatabaseName(connParams);
        log->print("Attempting to connect to database: " + connParams);
        if(!db.open()) {
            log->printerr("Could not connect to database: " + db.lastError().text());
            connected = false;
            ErrorWindow(0, "Database connection could not be establishedn" + db.lastError().text());
               return false;
            } else {
                log->print("Database connection established.");
                connected = true;
                SuccessWindow(0, "Database connection established");
                return true;
            }
        } else {
            ErrorWindow(0, "Driver not available or valid.");
        }
    } return true;
}

void DatabaseConnection::disconnect() {
    if (db.isOpen()) {
        db.close();
    }
}

void DatabaseConnection::loadParams() {
    QFile settings("dbSettings.txt");
    if (!settings.open(QIODevice::ReadOnly | QIODevice::Text)) {
        server = QString("Server String");
        database = QString("Database String");
        username = QString("Username");
        password = QString("Password");
    } else {
        QTextStream in(&settings);
        server = in.readLine();
        database = in.readLine();
        username = in.readLine();
        password = in.readLine();
    }
}

void DatabaseConnection::updateParams(QString params) {
    disconnect();
    QStringList parameters = params.split(";");
    server = parameters[0];
    database = parameters[1];
    username = parameters[2];
    password = parameters[3];
}

void DatabaseConnection::sendData(QString mode, QVector<QString> *data) {
    log->print("Prepping Data for Sending...");
    int cols;
    if(connectDB()) {
        db.exec(QString("USE " + database));
        QVector<QString> *dataQueue = new QVector<QString>;
        //collect all the data
        if (mode == QString("DK")) {
            extractData(mode, 15, 31, dataQueue, data);
            cols = 15;
        } else if (mode == QString("PQ")) {
            extractData(mode, 17, 200, dataQueue, data);
            cols = 17;
        } else {
            extractData(mode, 6, 200, dataQueue, data);
            cols = 6;
        }
        //create a query for each entry
        for (int i =0; i < (dataQueue->size() / cols); i++) {
            QString query("INSERT INTO ");
            emit requestConsts();
            if (mode == QString("Reg")) {
                 query += "RegTable(Project_ID, Project_Name, Cycle, Number, B1, B2, B3, Horiz, Vert, Skew) VALUES (";
            } else if (mode == QString("PQ")) {
                query += "PQTable(Project_ID, Project_Name, Cycle, Number, B1, B2, B3, [3DOTCD128_ScoreA], [3DOTCD128_GradeA],"
                     " [3DOTCD128_ScoreB], [3DOTCD128_GradeB], [10CR3DT128_Score], [10CR3DT128_Grade], [12CHAR3DOT39_Score],"
                     " [12CHAR3DOT39_Grade], [12CHAR4DOT39_Score], [12CHAR4DOT39_Grade], [2DOTDATAMATRIX_Score],"
                     " [2DOTDATAMATRIX_Grade], [3DOTDATAMATRIX_Score], [3DOTDATAMATRIX_Grade]) VALUES (";
            } else {
                 query += "DKTable(Project_ID, Project_Name, Cycle, Darkness, [3DOTCD128_ScoreA], [3DOTCD128_GradeA],"
                     " [3DOTCD128_ScoreB], [3DOTCD128_GradeB], [10CR3DT128_Score], [10CR3DT128_Grade], [12CHAR3DOT39_Score],"
                     " [12CHAR3DOT39_Grade], [12CHAR4DOT39_Score], [12CHAR4DOT39_Grade], [2DOTDATAMATRIX_Score],"
                     " [2DOTDATAMATRIX_Grade], [3DOTDATAMATRIX_Score], [3DOTDATAMATRIX_Grade]) VALUES (";
            }
            query += "" + constants;
            for (int j = 0; j < cols; j++) {
                int index = (i * cols) + j;
                query += ", " + dataQueue->at(index);
            }
            query += (")");
            log->print(query);
            QSqlQuery postedQuery = QSqlQuery(db);
            if (!postedQuery.exec(query)) {
                AlertWindow(0, this->lastError().text());
            }
        }
        //push the queries into action if not already being performed
        db.exec(QString("GO"));
        log->print("Data Sent.");
        SuccessWindow(0, "Data (theoretically) Sent!");
    }
}

void DatabaseConnection::getConsts(QString consts) {
    constants = consts;
}

void DatabaseConnection::extractData(QString mode, int cols, int rows, QVector<QString> *queue, QVector<QString> *data) {
    log->print("Extracting Data...");
    log->print(mode + " Mode");
    for (int row = 0; row < rows; row++) {
        QVector<QString> thisLine;
        for (int col = 0; col < cols; col++) {
            int index = (row * cols) + col;
            thisLine.append(data->at(index));
        }
        if (mode == QString("DK")) {
            if (!thisLine.at(0).isEmpty() && (!thisLine.at(1).isEmpty() || !thisLine.at(3).isEmpty() || !thisLine.at(5).isEmpty() || !thisLine.at(7).isEmpty() || !thisLine.at(9).isEmpty() || !thisLine.at(11).isEmpty() || !thisLine.at(13).isEmpty())) {
                for (int i = 0; i < cols; i++) {
                    queue->append(thisLine.at(i));
                    //log->print(thisLine.at(i));
                }
            }
        } else if (mode == QString("PQ")) {
            if ((!thisLine.at(0).isEmpty() && !thisLine.at(1).isEmpty() && !thisLine.at(2).isEmpty()) || (!thisLine.at(5).isEmpty() || !thisLine.at(7).isEmpty() || !thisLine.at(9).isEmpty() || !thisLine.at(11).isEmpty() || !thisLine.at(13).isEmpty() || !thisLine.at(15).isEmpty())) {
                for (int i = 0; i < cols; i++) {
                    queue->append(thisLine.at(i));
                    //log->print(thisLine.at(i));
                }
            }
        } else {
            if ((!thisLine.at(0).isEmpty() && !thisLine.at(1).isEmpty() && !thisLine.at(2).isEmpty()) || (!thisLine.at(3).isEmpty() || !thisLine.at(4).isEmpty() || !thisLine.at(5).isEmpty())) {
                for (int i = 0; i < cols; i++) {
                    queue->append(thisLine.at(i));
                    //log->print(thisLine.at(i));
                }
            }
        }
    }
}

Edit 6/21/16 - I've done some more research and found out I was using the DSN parameter incorrectly. My problem still stands even when I use it properly though, so no too much progress there, just some handy dandy learning.

Aucun commentaire:

Enregistrer un commentaire