Using Qt 4.8.6 and clang++ x86_64-apple-darwin14.3.0 on my late-2014 MacBook Pro I find that QsqlTableModel::insertRecord() fails to write the target MYSQL database: myDB while constructing the QSqlDatbase: myDB using a non-default connection such as:
db = QSqlDatabase::addDatabase("QMYSQL","Connection1");
and insertRecord(-1,myRecord) evaluates to false.
Instead, if I use the usual default connection:
db = QSqlDatabase::addDatabase("QMYSQL");
the database is appended successfully as:
mysql> select * from myTable;
+------+------+
| col1 | col2 |
+------+------+
| 1 | 2 |
| 5 | 6 |
+------+------+
2 rows in set (0.00 sec)
The usual recommendation to accommodate multiple connection names is to construct QSqlQuery with QSqlDatabase as:
QSqlQuery query(db)
that evidently doesn't seem to help in this case. Can you point out what's missing?
The small amount of runnable code that exemplifies the above is below:
testdb.h
#ifndef TESTDB_H
#define TESTDB_H
#include <QtSql>
#include <QtCore>
class TestDB
{
public:
TestDB();
~TestDB();
void dbInit();
void appendDB(const int &col1, const int &col2);
private:
QSqlDatabase db;
QSqlTableModel *model;
};
#endif // TESTDB_H
testdb.cpp
#include "testdb.h"
TestDB::TestDB()
{
dbInit();
}
TestDB::~TestDB()
{
}
void TestDB::dbInit()
{
// database connection
db = QSqlDatabase::addDatabase("QMYSQL","Connection1");
db.setDatabaseName("myDB");
db.setUserName("root");
db.setPassword("");
db.setHostName("localhost");
db.setConnectOptions();
if (!db.open())
{
qDebug() << "Database error occurred in class: stockinfo" << db.lastError().text();
}
QSqlQuery query(db);
// create database named transactions
query.exec("CREATE DATABASE IF NOT EXISTS myDB;");
query.exec("USE myDB;");
query.exec("CREATE TABLE IF NOT EXISTS myTable("
"col1 INT,"
"col2 INT"
");");
model = new QSqlTableModel;
model->setTable("myTable");
model->select();
}
void TestDB::appendDB(const int &col1, const int &col2)
{
QSqlRecord myRecord;
myRecord.append(QSqlField("col1", QVariant::Int));
myRecord.append(QSqlField("col2", QVariant::Int));
myRecord.setValue("col1",col1);
myRecord.setValue("col2",col2);
model->insertRecord(-1,myRecord);
qDebug() << "model->insertRecord(-1,myRecord) = " << model->insertRecord(-1,myRecord);
qDebug() << "Last Database error: " << db.lastError().text();
}
main.cpp
#include <QCoreApplication>
#include <testdb.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
TestDB myTestDB;
myTestDB.appendDB(1,2);
myTestDB.appendDB(5,6);
return a.exec();
}
dbTest.pro
QT += core sql
QT -= gui
TARGET = dbTest
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
testdb.cpp
HEADERS += \
testdb.h
QSqlQuerywithQSqlDatabase. Nevertheless, the approach suggested in your link produces the same problem.