0

I've already got an infrastructure to work with. There is an insert function given with the following signature:

insert(const QString& key, const QVariant& value)

Within the function the QSqlQuery is getting prepared:

QSqlQuery query{mySqlDatabase};
QString sql = "INSERT INTO my_table(key, value) VALUES (:key, :value)"
query.prepare(sql);
query.bindValue(ENC(":key"), key);
query.bindValue(ENC(":value"), value.toString());

if (!query.exec()) {
    const auto error = q2.lastError();
    throw std::exception(QString("failed to insert: %1")).arg(error.text()));
}

This works for all the insertions used so far, but now I'm trying to insert a QVariantMap (which is a typedef for QMap<QString,QVariant>, in fact I'm trying to save QMap<QString,int> type):

insert(g_theKey, QVariant(m_theMap));

Upon query execution I'm receiving the following error:

enter image description here

I was looking for solutions on both the Qt website and here, but haven't found a working solution.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Attis
  • 573
  • 1
  • 7
  • 19
  • What kind of field is "value"? – eyllanesc May 07 '21 at 13:46
  • It is QVariant& – Attis May 07 '21 at 13:54
  • Hmm, you don't seem to understand me. "my_table" is a table in the database so my question is what type of data is the field "value" of the table "my_table"? The same for "key". In the DB there is no type QVariant – eyllanesc May 07 '21 at 13:56
  • That expects a string. That part of the functionality is not my concern, because as stated above that function works for other types, but it does not work for QVariantMap. – Attis May 07 '21 at 13:59
  • What are those "other types"? – eyllanesc May 07 '21 at 14:01
  • I think I found what was wrong. According to Qt documentation: QString QVariant::toString() const - Returns the variant as a QString if the variant has type() String, Bool, ByteArray, Char, Date, DateTime, Double, Int, LongLong, StringList, Time, UInt, or ULongLong; otherwise returns an empty string. Basically, QVariantMap can't be stringified. So my solution, for now, is to stringify and de-stringify the QVariantMap manually. – Attis May 07 '21 at 14:03
  • 1
    Exactly, is what I was going to point out to you – eyllanesc May 07 '21 at 14:03
  • For the purpose of serializing QMap object I found this article: https://stackoverflow.com/questions/27285889/how-do-you-serialize-a-qmap – Attis May 12 '21 at 14:58

0 Answers0