Qt ODBC driver crashes on QDatabase::open() OS X - c++

While trying to connect to a MS SQL database the app crashes.
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setHostName("test");
db.setDatabaseName("test");
db.setUserName("test");
db.setPassword("test");
qDebug() << "Is driver available:" << db.isDriverAvailable("QODBC");
qDebug() << "Drivers:" << db.drivers();
qDebug() << "Db is valid:" << db.isValid();
qDebug() << "Last error:" << db.lastError();
if (!db.open()) // Crashes here
qDebug() << "Database error";
I saw some posts where unixODBC and FreeTDS is a solution but I was unable to get it working.
The output of qDebug() calls is:
Is driver available: true
Drivers: ("QSQLITE", "QMYSQL", "QMYSQL3", "QODBC", "QODBC3", "QPSQL", "QPSQL7")
Db is valid: true
Last error: QSqlError("", "", "")

Related

How to create secure https server in "Qt"?

I am going through the below github source code for implementation of rest server. It has details with respect to http server but when I am trying to create a secure server I am facing problem after adding the certificate and key. Please suggest how to establish a secure https server using Qt.
https://github.com/Tropby/QSimpleRestServer
QFile certFile("demo.cer");
QFile keyFile("demo.key");
QByteArray cert,key;
if(!certFile.open(QIODevice::ReadOnly))
{
qDebug() << "Couldn't Open Resource File.";
qDebug() << "Error: " << certFile.errorString();
}
else {
cert = certFile.readAll();
certFile.close();
}
if(!keyFile.open(QIODevice::ReadOnly))
{
qDebug() << "Couldn't Open Resource File.";
qDebug() << "Error: " << keyFile.errorString();
}
else {
key = keyFile.readAll();
keyFile.close();
}
if(sslSocket->setSocketDescriptor(socket_descriptor)){
qDebug()<<"set passed";
} else {
qDebug()<<"set failed";
}
sslSocket->setProtocol(QSsl::AnyProtocol);
sslSocket->ignoreSslErrors();
QSslKey ssl_key(key,QSsl::Rsa,QSsl::Pem,QSsl::PrivateKey,(QByteArray)"demo.key");
QSslCertificate ssl_cert(cert);
sslSocket->setLocalCertificate(cert);
sslSocket->setPrivateKey(ssl_key);
sslSocket->modeChanged(QSslSocket::SslMode::SslServerMode);
sslSocket->startServerEncryption();

QSqlTablelModel cannot find SQL view, but QSqlQuery can

I want to use QSqlTableModel since it seems easier to use. It does however not find my tables.
qDebug() << "connecting";
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName(dbHostName);
db.setPort(dbPort);
db.setUserName(dbUserName);
db.setPassword(dbPassword);
// Connect to database sys to get some info to test (basic communication)
db.setDatabaseName("sys");
// Check if opened and if so get some data
if(db.open()){
qDebug() << "DB succesfully opened";
} else {
qDebug() << "DB failed to open";
return;
}
QSqlTableModel* runsSimulationViewModel = new QSqlTableModel();
runsSimulationViewModel->setTable("results.runs_simulation_view");
qDebug() << runsSimulationViewModel->lastError();
//ERROR: QSqlError("", "Unable to find table results.runs_simulation_view", "")
QSqlQuery anotherQuery;
anotherQuery.prepare("SELECT * FROM results.runs_simulation_view");
if(!anotherQuery.exec()) {
qDebug() << anotherQuery.lastError();
} else {
anotherQuery.next();
qDebug() << anotherQuery.value("simulation_id").toInt();
//Prints "3", which is the first value for this field in the table
}
QSqlQuery works, but QSqlTableView cannot find this (SQL) view (and also no tables).
What am I missing?

How to check database is exist or not?

I am using sqlite database in qt. Database created when i use setDatabase("") function. But i dont know how to check same database is exist or not. Here is my code:
//add database driver
db = QSqlDatabase::addDatabase ("QSQLITE");
//create database
if(db.databaseName () == db_Name){
qDebug() << "Database exist or not created." << endl;
} else {
db.setDatabaseName (db_Name);
qDebug() << "Database created." << endl;
}
//opening connection
db.open ();
//if connection created
if(db.isOpen ()){
qDebug() << "Database connected." << endl;
} else {
qDebug() << "Database not connected." << endl;
}
I get the Database created. message. How to check ? Thanks.
You can simply check the database file whether it exists using QFile:
if (QFile::exists(db_Name)) {
// database exists
}
SQLite creates an empty database when you try to open a nonexisting file.
So if you want to know if you need to create the tables for your application, just run a query to check whether these tables exist:
SELECT * FROM sqlite_master WHERE name = 'MyTable';

Catching SQL errors using Qt

The code below doesn't work for catching sql errors with Qt and sqlite. I've also tried isNull. I'm getting a blank string for lasterror.text() and -1 for error number with working queries. I don't understand why isEmpty or isNull aren't working.
if (!query.lastError().text().isEmpty())
{
logfile(sqlstatement);
logfile("SqLite error:" + query.lastError().text());
logfile("SqLite error code:"+ QString::number( query.lastError().number() ));
}
Do you really execute your query?
Take a look at way of doing access do SQLite DB + logging in OpenSource application Mixxx (Opening database, applying query):
...
#define LOG_FAILED_QUERY(query) qDebug() << __FILE__ << __LINE__ << "FAILED QUERY [" \
<< (query).executedQuery() << "]" << (query).lastError()
...
// Check if you have QSQLITE2/QSQLITE driver avaiable
qDebug() << "Available QtSQL drivers:" << QSqlDatabase::drivers();
m_db.setHostName(...);
m_db.setDatabaseName(...);
m_db.setUserName(...);
m_db.setPassword(...);
bool ok = m_db.open();
qDebug() << "DB status:" << m_db.databaseName() << "=" << ok;
if (m_db.lastError().isValid()) {
qDebug() << "Error loading database:" << m_db.lastError();
}
...
QSqlQuery query(m_database);
query.setForwardOnly(true);
query.prepare(queryString);
if (!query.exec()) {
LOG_FAILED_QUERY(query);
return;
}
And be sure that this works :)

mysql cpp connector throwing UnknownException while connecting

I am using mysql library to connect to my database (mysql) to retrieve the data after connecting. Checked that my services are running properly.
Following is the part of code that does the connecting task..
// Specify our connection target and credentials
const string server = "tcp://127.0.0.1:3306";
const string username = "root";
const string password = "";// No password - thanks, WAMP Server!
// Try to get a driver to use to connect to our DBMS
try {
driver = get_driver_instance();
if( driver == NULL )
throw SQLException("Null driver instance returned.");
}
catch (SQLException e) {
cout << "Could not get a database driver. Error message: " << e.what() << endl;
return -3;
}
// Try to connect to the DBMS server
try {
dbConn = driver->connect(server, username, password);
}
catch (sql::SQLException e) {
cout << "Could not connect to database. Error message: " << e.getSQLStateCStr() << " Error Code: " << e.getErrorCode() << endl;
cout << "Could not connect to database. Error: " << e.what() << endl;
return -1;
}
It compiles well but gives an unknown exception with unknown debug info. Something like this. Please help.
This worked after changing the string to SQLString for all the connection params like server, username and password.
This worked out like a charm.