在Qt中向MySQL数据库提交QSqlRecord

时间:2022-10-13 09:19:25

I want to access a MySQL database and I want to read+write data from+to the database within my Qt/C++ program. For the read write process, I try to use QSqlTableModel, QSqlTableRcord and QSqlDatabase as this is a very pleasant approach without too much of SQL commands which I dislike for the one or other reason (to handle myself). I got a similar approach already running (so the database is running already) but it is cluttered all over. So the simple question is what am I doing wrong within these few lines of example code: Using QT 4.5.x The test database has 3 columns: float x, float y, blob img

我想访问MySQL数据库,我想在Qt/ c++程序中从+读取+写入数据。对于读写过程,我尝试使用QSqlTableModel、QSqlTableRcord和QSqlDatabase,因为这是一种非常令人愉快的方法,没有太多SQL命令(出于某种原因,我不喜欢这些命令)。我已经在运行类似的方法(因此数据库已经在运行),但它到处都是杂乱的。因此,简单的问题是,在这几行示例代码中,我做错了什么:使用QT 4.5。测试数据库有3列: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;
    }

Thx for any help, I already run from one end of the Qt docs to the other but did not find a solution and I already wasted 5 hours doing that, so I am thankful for any hint (unless you suggest to do it completely different).

对于任何帮助,我已经从Qt文档的一端跑到另一端,但是没有找到解决方案,我已经浪费了5个小时,所以我感谢任何提示(除非你建议做完全不同的事情)。

1 个解决方案

#1


6  

Your QSqlRecord doesn't have any fields defined. You need to add

QSqlRecord没有定义任何字段。您需要添加

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

before you set the values

在设置值之前

#1


6  

Your QSqlRecord doesn't have any fields defined. You need to add

QSqlRecord没有定义任何字段。您需要添加

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

before you set the values

在设置值之前