开发者

Submitting QSqlRecord to MySQL database in Qt

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

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).


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

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

before you set the values


Use your table to generate the record, qt will automatically create the fields contained by the table.

QSqlTableModel table;
table.setTable("test_table");
QSqlRecord rcd = table.record();
rcd.setValue("x",1.0f);
rcd.setValue("y",2.0f);

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

model.insertRecord(-1,rcd);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜