Sending QSqlRecord to MySQL database in Qt

I want to access a MySQL database, and I want to read + write data from + to a database in my Qt / C ++ program. For the reading process, read, I'm trying to use QSqlTableModel, QSqlTableRcord and QSqlDatabase, since this is a very nice approach without too many SQL commands that I don’t like for one reason or another (for processing myself). I already have a similar approach (so the database is already running), but it is cluttered. So the simple question is what I'm doing wrong in these few lines of sample code: Using QT 4.5.x There are 3 columns in the test database: float x, float y, blob img

int main(){
QImage img("./some_image.png");
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("test");
db.setPort(3306);
db.setUserName("root");
db.setPassword("xxxxxxx");
if (!db.open() )
    qDebug("Mising db / unable to open");
else {
    QSqlTableModel model;
    qDebug() << "tables::" <<db.tables(); //so I see the table exists and gets detected
    model.setTable("test_table");

    QSqlRecord rec;
    rec.setValue(0,1.0f);
    rec.setValue(1,2.0f);

    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    img.save(&buffer, "PNG");
    rec.setValue(2,ba);

    model.insertRecord(0,rec);
    qDebug() << model.lastError().text();
    if (!model.submitAll())
        qDebug() << "Submit all did not work";
    return 0;
    }

, Qt- , , 5 , ( ).

+3
1

QSqlRecord .

rec.append(QSqlField("x", QVariant::Double));
rec.append(QSqlField("y", QVariant::Double));
rec.append(QSqlField("img", QVariant::Image));

+6

Source: https://habr.com/ru/post/1722014/


All Articles