简体   繁体   中英

Qt - GUI Database programming

I am using Qt GUI to save data in MySQL using C++.

I am using QDateTimeEdit widget for this. Whatever the value changed by user in GUI of QDateTimeEdit , it should be inserted in MySQL.

Can anyone tell me how to do that?

How to access value from QDateTimeEdit and converting it in proper format like QString and using MySQL query inserting it into database?

An alternative is not to convert it to a QString but let the driver do that for you. If you expect some precision in the conversion some cases this might be better, other cases it can be worse:

QDateTime date = ui->dateTimeEdit->dateTime();
QSqlQuery query(myDatabase);
query.prepare("INSERT INTO my_table (id, date) "
              "    VALUES (:id, :date)");
query.bindValue(":id", 1001);
query.bindValue(":date", date);
query.exec();

The QSqlQuery::bindValue() function will take the QDateTime and pass it through as a QVariant and then the driver should know how to convert a QVariant::DateTime to the correct string that the database understands.

About second part "how to access value":

You somehow in code created object of QDateTimeEdit and place it on some layout. Typically it will be pointer with name for example mpDTPicker.

QDateTimeEdit * mpDTPicker = new QDateTimeEdit();
//place mpDTPicker on layout.

For access current time we need use method dateTime :

//User actions with date -> emitted signal -> execute slot with our logic
{
    QDateTime momentum = mpDTPicker->dateTime();
// So here we need convert QDateTime to QString and we will use [toString Method](http://doc.qt.io/qt-4.8/qdatetime.html#toString)
    QString result_string = momentum.toString("dd:mm:yy");
    QDebug() << result_string;
}

So that is all about converting QDateTime to QString. About first part of Question how to get that user changed value of DateTimeEdit is total another question.

And about third part how to store it in mysql database everything depended on structure of your table. But typicaly it can be solved with simple query :

QSqlQuery query;
QString mQuerry = "INSERT INTO mytable (id, date) VALUES (0, \"" +result_string "\" )";
query.exec(mQuerry);

And please READ DOCS especial when them so cool :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM