difference between null QString and empty QString

A null QString is an uninitialized QString while an empty QString is a QString initialized with an empty string(reference).

QString s1;
QString s2("");
if(s1==s2)
  qDebug()<<"same";//same
else
  qDebug()<<"not same";
qDebug()<<s1.isNull();//true
qDebug()<<s1.isEmpty();//true
qDebug()<<s2.isNull();//false
qDebug()<<s2.isEmpty();//true

A NULL QString is almost the same as an empty QString except isNull returns true for a NULL QString but returns false for an empty QString.

I never realized the difference between if a QString is empty and NULL until I got an error when inserting an empty string to a database table that requires the column not null.

Column ‘col1’ cannot be null QMYSQL3: Unable to execute statement

QString sql = "insert into table3 values(:col);";
QSqlQuery query;
query.prepare(sql);
QString col;
query.bindValue(":col",col);
if(!query.exec())
{
    qDebug()<<query.lastError().text();
    exit(1);
}

Here, the table field col1 has a NOT NULL constraint but we use the QSqlQuery::bindValue function to bind the placeholder :col to a NULL QString, which results in the error.  The null QString is converted to a NULL QVariant, i.e., QVariant(QVariant::string). To insert an empty string instead of a null value into the table, you should use the empty QString instead of the null QString, i.e.,

QString sql = "insert into table3 values(:col);";
QSqlQuery query;
query.prepare(sql);
QString col("");
query.bindValue(":col",col);
if(!query.exec())
{
    qDebug()<<query.lastError().text();
    exit(1);
}
Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Leave a Reply