How to save QTime in SQL Server Express table and

2019-05-01 14:32发布

问题:

I have a table in SQL Server Express with fields name varchar(10) and timeVar time and I want to save the value of a QTime variable in the time field.

This is what I have tried:

QTime time = QTime::currentTime();
QString timeString = time.toString("hh:mm:ss");
QString query = QString("insert into timeHold(name,timeVar) values ('ABC','%2')").arg(timeString);

qry->prepare(query);
qry->exec();

However, I get QSqlQuery::value: not positioned on a valid record.

When I insert values into the table from SQL Server Management Studio, insert into timeHold values('XYZ', '12:17:35') works perfectly. To my surprise though, when I have tried reading the values stored in the table from the management studio, I was able to get the name field, but not time field.

Here is the code I use to read values from the table:

QString query = QString("select * from timeHold");

qry->prepare(query);
qry->exec();
qry->first();

int noOfRecords = qry->numRowsAffected();

do {
    qDebug() << qry->value(0).toString();
    qDebug() << qry->value(1).toString();
} while (qry->next());

The code produces the following output:

"ABC"
"\u0017"
"world"
"\u000B"
"Mama"
"\u000B"
"Gerama"
"\u000B"

How can I make it work?

回答1:

For the saving story , I would say the arg method does not work because you ask for %2 but there is only one element to substitute

   query = QString("insert into timeHold(name,timeVar) values ('ABC','%2')").arg(timeString);

I think it should be

query =  QString("insert into timeHold(name,timeVar) values ('ABC','%1')").arg(timeString);

For retrieving from the DB, it's either because you have to specify the format when inserting or when reading