How can I get sqlite error code from Qt - c++

I use sqlite database in my Qt program.
QSqlDatabase db;
db = QsqlDatabase::addDatabase("QSQLITE");
When I can not get data from sqlite db.lastError() function always return same thing
QSqlError(-1, "Driver not Loaded", "Driver not loaded")
How can I get sqlite error codes from Qt?
upd1:
QSqlQuery query;
query.exec(QString("select NAME from PEOPLE where AGE=%1").arg(age));
if(query.next())
{
}
else
{
//check for sqlite error
}

The best you can do with the Qt API itself is the following method:
int QSqlError::number() const
Returns the database-specific error number, or -1 if it cannot be determined.
See how the error codes from sqlite are handled in the driver codebase itself:
https://qt.gitorious.org/qt/qtbase/source/eb5c0f4b1266702c016b032e281bb92a3a642da6:src/sql/drivers/sqlite/qsql_sqlite.cpp#L324
You can see that the corresponding QSqlError constructor is used for that with passing the low-level error code to it as the last argument which you can obtain with the aforementioned method.
As you can see, it is not handling all the low-level errors similarly, but there is a default switch case in there for the rest. Even in the latter case, the errors are passed to the constructor.
You need to be aware of that, oftentimes, it cannot determine the exact low-level error in which case it will return -1 as per documentation.
Putting this into practice, you would be writing something like this:
QSqlQuery query;
query.exec(QString("select NAME from PEOPLE where AGE=%1").arg(age));
if (query.next())
{
} else {
qDebug() << "SqLite error:" << query.lastError().text() << ", SqLite error code:" << query.lastError().number();
}

Related

QT open not existing database

I've created simple function for connecting with sqlite3 database. But I've recognized that it makes connection , even if database file not exist
As you can see below : I've tried to check if file really exist and if it's really connected .
bool DatabaseConnection::make_connection(const QString &path)
{
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(path);
#ifdef QT_DEBUG
qDebug() << "File: '" + db.databaseName() + "' exist = " << QFileInfo::exists(db.databaseName());
qDebug() << db.isValid();
#endif
if (!db.open())
{
QMessageBox::critical(nullptr,
QObject::tr("Error - Cannot open database"),
QObject::tr("Failed attempt to establish connection \n"),
QMessageBox::Close);
return false;
}
qDebug() <<"Open:" <<db.isOpen();
qDebug() << "errors:" << db.isOpenError();
return true;
}
after changing path name on first compilation - file not exist , but connection seems to be established (True).
In next compilation tells that file exist ( I've couldn't find it anywhere) , and again connection is 'established'
I had similar problem, db.open() creates new file if it doesn't exist.
Just wrap db.open() arround QFileInfo::exists(path).
I believe if you attempt to access an SQLite3 database that does not exist, it will create one. So db.open() will attempt to create a database file if one is not found. You would be best served checking if the DB file exists first using some other method before calling db.open().

How to deploy Qt application with an existing Sqlite db?

I want to package my Qt application with an existing Sqlite db. I have the standard Qt database code:
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName("database.sqlite");
bool connected = m_db.open();
if (!connected) {
qDebug() << "Error: connection with database failed";
} else {
qDebug() << "Database: connection success";
QSqlQuery q(m_db);
q.prepare("SELECT * FROM people");
if (q.exec()) {
qDebug() << "Yay!";
} else {
qWarning() << "Bad exec: " << q.lastError();
qWarning() << q.executedQuery();
}
}
However, the result is:
Error: connection with database failed
I know this is because it's not finding the correct database, and is instead creating a new one. If I provide the absolute path on my development machine to m_db.setDatabaseName(), it works. But my database file is in my .qrc and will not be available in that location when I deploy... so how can I get a reliable path for this database?
in the setDatabaseName-call use the right syntax for resource files:
m_db.setDatabaseName(":database.sqlite"); // <-- note the : before the name
... presuming the database file is located in the root of your resource file system.
Greetings, Thomas

How to get data from intersystems cache db through ODBC?

This is how i try to get a data from db:
#include <QCoreApplication>
#include <QtCore>
#include <QtSql>
#include "iostream"
int main(int argc, char *argv[])
{
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={InterSystems ODBC};SERVER=localhost;PORT=1972;DATABASE=USER;UID=_system;PWD=SYS; Unicode SQLTypes=1;");
if (!db.open())
{
std::cout << "Error opening database" << std::endl;
return -1;
}
else
{
QSqlQuery query;
if(query.exec("SELECT * FROM ACCOUNTS")){
std::cout << "Select succses!" << std::endl;
}
while (query.next())
{
std::cout << "Getting results..." << std::endl;
std::cout << query.value(0).toString().toStdString() << std::endl;
}
std::cout << "EXIT!" << std::endl;
return 0;
}
}
And after query.exec(...) query.next() is always false but I really know that there is a data in the table. This behavior reproduce in the case when I try to get data from sample tables of Cache DB. What did i do wrong?
Thanks for your help.
The problem was that connection config is wrong:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
db.setDatabaseName("DRIVER={InterSystems ODBC};SERVER=localhost;PORT=1972;DATABASE=USER;UID=_system;PWD=SYS; Unicode SQLTypes=1;");
it should be:
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC3");
db.setDatabaseName("DRIVER={InterSystems ODBC35};SERVER=localhost;PORT=1972;DATABASE=USER;UID=_system;PWD=SYS; Unicode SQLTypes=1;");
[as I said in the comments, I'm not familiar with this API Just looking through the documentation as I answer]
the documentation for the constructor of QSqlQuery
Constructs a QSqlQuery object using the SQL query and the database db.
If db is not specified, or is invalid, the application's default
database is used. If query is not an empty string, it will be
executed.
This means your query is opened on the default database (whatever that means).
Looking at the QSqlDatabase documentation:
QSqlDatabase also supports the concept of a default connection, which
is the unnamed connection. To create the default connection, don't
pass the connection name argument when you call addDatabase().
however, you're giving a name argument in your addDatabase():
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
... that means it is not the default connection.
My guess is that you should either:
QSqlDatabase db = QSqlDatabase::addDatabase();
or
QSqlQuery query=QSqlQuery(db);

Can't connect to SQL database with mysql++

I've been trying to use the mysql++ library in my application (windows x64 based) but I can't seem to connect to my sql server.
Some information:
I used this code to connect to the server:
mysqlpp::Connection conn(db, 0, user, pass, 3306);
this definitely has the right data in it.
and then, my sql server is the standard service from the MySQL install. And I'm pretty sure I used the standard settings. I can connect to it using the MySql Workbench and I edited some new tables and such but my own program doesn't seem to connect.
I read the documentation and I can't find anything specific that might suggest something why I can't connect.
Oh, so many issues, so little time...
Have you checked that your program has permissions to access the database?
Does your program have the correct privileges?
Is your host name correct?
What errors are you getting?
What exception is thrown?
When you use the debugger, what line is the error on?
Here's my method:
sql::Connection * const
Manager ::
get_db_connection(void) const
{
//-------------------------------------------------------------------------
// Use only one connection until proven that more connections will make
// the program more efficient or have a beneficial impact on the user.
// Thus the change in returning sql::Connection * rather than a smart pointer.
// A smart pointer will delete its contents.
//-------------------------------------------------------------------------
static const char host_text[] = "tcp://127.0.0.1:3306/";
static std::string host_name;
if (!m_connection_initialized)
{
host_name = host_text;
initialize_db_driver();
host_name += m_dataset_info.m_dsn_name;
try
{
m_p_connection = m_p_sql_driver->connect(host_name.c_str(),
m_dataset_info.m_user_name.c_str(),
m_dataset_info.m_password.c_str());
}
catch (sql::SQLException &e)
{
/*
The MySQL Connector/C++ throws three different exceptions:
- sql::MethodNotImplementedException (derived from sql::SQLException)
- sql::InvalidArgumentException (derived from sql::SQLException)
- sql::SQLException (derived from std::runtime_error)
*/
wxString wx_text = wxT("# ERR: SQLException in ");
wx_text += wxT(__FILE__);
wxLogDebug(wx_text);
wx_text.Printf(wxT("# ERR: (%s) on line %d"),
__FUNCTION__,
__LINE__);
wxLogDebug(wx_text);
wx_text.Printf(wxT("# ERR: %s (MySQL error code: %d, SQLState: %s)"),
e.what(),
e.getErrorCode(),
e.getSQLState());
wxLogDebug(wx_text);
wxLogDebug(wxT("Verify that mysqlcppconn.dll is in the PATH or in the working directory."));
// throw Manager_Connection_Not_Initialized();
m_connection_initialized = false;
}
catch (...)
{
std::cout << "Unhandled database SQL exception\n" << flush;
m_connection_initialized = false;
}
m_connection_initialized = true;
}
return m_p_connection;
}

libmysqlclient.18.dylib memory leak

PROBLEM: What's the cause of the memory leaks?
SITUATION:
I've build a simple command line program using C++ together with MySQL using the MySQL C API
The problem is, the program has many "minor" memory leaks from the object malloc xx bytes" with xx ranging from a few bytes to 8 kb. All of the leaks links to the library libmysqlclient.18.dylib.
I've already removed all the mysql_free_result() from the code to see if that was the problem, but its still the same.
My MySQL code mainly consists of simple code like:
to connect:
MYSQL *databaseConnection()
{
// declarations
MYSQL *connection = mysql_init(NULL);
// connecting to database
if(!mysql_real_connect(connection,SERVER,USER,PASSWORD,DATABASE,0,NULL,0))
{
std::cout << "Connection error: " << mysql_error(connection) << std::endl;
}
return connection;
}
executing a query:
MYSQL_RES *getQuery(MYSQL *connection, std::string query)
{
// send the query to the database
if (mysql_query(connection, query.c_str()))
{
std::cout << "MySQL query error: " << mysql_error(connection);
exit(1);
}
return mysql_store_result(connection);
}
example of a query:
void resetTable(std::string table)
{
MYSQL *connection = databaseConnection();
MYSQL_RES *result;
std::string query = "truncate table " + table;
result = getQuery(connection, query);
mysql_close(connection);
}
First of all: Opening a new connection for every query (like you're doing in resetTable()) is incredibly wasteful. What you really want to do is open a single connection when the application starts, use that for everything (possibly by storing the connection in a global), and close it when you're done.
To answer your question, though: You need to call mysql_free_result() on result sets once you're done with them.