I want to insert the data of a (custom) class "Table" into my database - the data is retrieved from internal files, but for the sake of security, I'd like to assume the sources are untrusted. Currently, I'm using a variation of the code below. This is obviously prone to SQL-injections as v.toString() might be exploited. table.getName() is checked against a table-whitelist, so there should be no need to defend against SQL-injections here.
QString rowQuery = "INSERT INTO " + table.getName() + " VALUES ";
for (Row* r : table) {
rowQuery += "(";
for (QVariant v : r.getValues()) {
rowQuery += v.toString();
rowQuery += ","
}
rowQuery.chop(1);
rowQuery += "),";
}
rowQuery.chop(1);
QSqlQuery::exec(rowQuery)
An example query with two entries with three columns looks like:
INSERT INTO DebugTable VALUES (cell1x1, cell1x2, cell1x3), (cell2x1, cell2x2, cell2x3)
To make my application secure against SQL-injections, I started using prepared statements. Unfortunately, performance suffered greatly from this design choice, so I tried to use batch executions using QVariantLists, but even this approach could not deliver appropriate performance. My largest table has 15,000 entries; without prepared statements the insertion (q.exec() / q.execBatch()) took around four seconds, with prepared statements it took 90 seconds.
QList<QVariantList> columnVectors;
QString queryString;
queryString = "INSERT INTO " + table.getName() + " VALUES (";
for (auto i : table.getCols()) {
columnVectors.append(QVariantList());
queryString += "?,";
}
queryString.chop(1);
queryString += ")";
for (Row* row : table.getRows()) {
for (int i = 0; i < row->getValues().length(); i++) {
columnVectors[i].append(variant);
}
}
QSqlQuery q;
q.prepare(queryString);
for (QVariantList columnVector : columnVectors) {
q.addBindValue(columnVector);
}
q.execBatch();
An example query with x entries with three columns looks like:
INSERT INTO DebugTable VALUES (?, ?, ?)
I think there might be an error in my approach / implementation as I read that prepared statements should improve the performance. Any help would be appreciated, thank you