QT open not existing database - c++

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

Related

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

Connecting to MS SQLServer from Qt Linux application

I'm trying to connect to a MS SQL Server on a remote box using QODBC in my Qt Linux application.
Here's what I have done so far:
Added QT += SQL in the .pro file.
Tested some db functions:
QStringList drivers = QSqlDatabase::drivers();
qDebug() << "Drivers: " ;
foreach(QString driver, drivers) {
qDebug() << ":: " << driver;
}
qDebug() << "Connection Names: ";
QStringList connames = QSqlDatabase::connectionNames();
foreach(QString conname, connames) {
qDebug() << ":: " << conname;
}
qDebug() << "---";
these both work, though connectionNames() is empty at this stage.
I have tried to added a database:
QString serverName = "server1";
QString dbName = "abc123";
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", "MyFirst");
db.setHostName(serverName);
QString myCon = QString("DRIVER={SQL Native Client};SERVER=%1;DATABASE=%2;Trusted_Connection = Yes").arg(serverName).arg(dbName);
db.setDatabaseName(myCon);
If I now list the connections, "MyFirst" is in the list.
Tried to open the database:
bool ok = db.open();
qDebug() << "OK: " << ok;
if (!ok) {
qDebug() << "error: " << db.lastError().text();
}
The db.open() fails with the following message:
"[unixODBC][Driver Manager]Can't open lib 'SQL Native Client' : file not found QODBC3: Unable to connect"
My questions are:
I picked up the connection string from a forum post, I figured it was as good a place to start as any, but what exactly should be in there? Where does "SQL NAtive Client" come from? What do I need to do to setup my Qt / Linux box to be able to connect to a remote MS SQL Server?
Sounds like you need to install the SQL Server ODBC Driver.
An explanation for how to do that is here:
https://technet.microsoft.com/en-us/library/hh568454(v=sql.110).aspx
In addition you need to refer to it by the correct name, which is "ODBC Driver 11 for SQL Server"

Trouble opening DB environment in Oracle Berkeley DB

I'm new to databases and I wrote this practice program to test Berkeley BDB. I'm getting trouble opening the environment - the error appears in my console and says:
testEnv\_db.001: No such file or directory
Error opening database environment
DbEnv::open: No such file or directory
The code of the console program is based strongly off the examples in the Berkeley DB Transactions guide, and here's the text of the program up to the error, under int main().
String^ key_allkeys = "_ALLKEYS";
String^ key_valcount = "_COUNT";
// 1. Print some information to the screen, prompt user to enter path for key-value pair location:
Console::WriteLine("Oracle Berkeley DB Example Database Creator");
Console::WriteLine();
Console::WriteLine("Enter the path to the text file of key-value pairs:");
String^ kv_path = Console::ReadLine();
// 2. Declare initial variables:
String^ totalkeys;
int totalval;
// 3. Open the database:
u_int32_t env_flags = DB_CREATE | DB_INIT_LOCK | DB_INIT_LOG | DB_INIT_MPOOL | DB_INIT_TXN;
std::string envHome("testEnv");
u_int32_t db_flags = DB_CREATE | DB_AUTO_COMMIT;
Db *dbp = NULL;
const char *file_name = "mydb.db";
DbEnv myEnv(0);
try
{
myEnv.open(envHome.c_str(), env_flags, 0);
dbp = new Db(&myEnv, 0);
dbp->open(NULL, file_name, NULL, DB_BTREE, db_flags, 0);
}
catch(DbException &e)
{
std::cerr << "Error opening database environment: " << std::endl;
std::cerr << e.what() << std::endl;
exc_block(); // Block
return (EXIT_FAILURE);
}
It should be fairly obvious that the program is failing right around the try/catch blocks. I've read the manual (literally RTFM) and I couldn't figure it out - the DB_CREATE flag is specified for both the environment and database, so there shouldn't be an issue here.
Any ideas?
It may simply be that the testEnv directory doesn't exist in the directory where you are running the program? You have to create the environment home directory yourself.
Also, you may wish to specify DB_RECOVER when opening the environment.

Qt how to get application to get md5 checksum of itself

Working on a Qt application. I'm trying to get the exe file to return an md5 checksum of itself while it's running. How can I do this?
I tried this:
QFile theFile("file.exe");
QByteArray thisFile;
if (theFile.open(QIODevice::ReadOnly))
{
thisFile = theFile.readAll();
}
else
{
qDebug() << "Can't open";
}
qDebug() << QString("%1").arg(thisFile.length());
fileMd5 = QString(QCryptographicHash::hash((thisFile), QCryptographicHash::Md5).toHex().toUpper());
qDebug() << fileMd5;
This does not return the correct value, however.
Update:
I got it working with other files. The problem seems to be that I am unable to read the exe while it's running.
Final update:
This is the solution:
QFile theFile(QCoreApplication::applicationFilePath());
QByteArray thisFile;
if (theFile.open(QIODevice::ReadOnly))
{
thisFile = theFile.readAll();
}
else
{
qDebug() << "Can't open file.";
}
QString fileMd5 = QString(QCryptographicHash::hash((thisFile), QCryptographicHash::Md5).toHex());
qDebug() << fileMd5;
You forgot to call open on theFile.
if (!theFile.open(QIODevice::ReadOnly))
// Handle error here
Also, you should be using QCoreApplication::applicationFilePath() to get the path to the executable.
You have to create an independent application (let's call it myApp) which check the MD5sum and compare it with your PHP script and ask for an update if needed or load directly the application.
Like so : myApp=> need update ? (update) : (TheRealApp)
Ok, looks like it just wasn't finding the file. I tried an absolute path instead of a relative and it worked. I'll have to figure out what's going wrong, but it looks like it can read itself while running.

Why can't I delete the SQLite database in Qt even after I call the database close function?

I'm writing a code to work with a SQLite database, all the code of the database works, but at end, when I try to delete the database, the database file is not deleted. I've called the close function, so why can't I delete the database?
The db.isOpen(); function returns false, and the QFile::remove(path); returns false too.
Note: On Windows Explorer i can delete the database only after closing the program window.
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
QString path = "path_to_db";
db.setDatabaseName(path);
if(db.open())
{
qDebug() << "Opened";
qDebug() << path;
}
else
{
qDebug() << db.lastError();
return a.exec();
}
QSqlQuery query(db);
//code to work with the database
db.close();
qDebug() << db.isOpen();
qDebug() << QFile::remove(path);
I found the solution, simply call query.clear(); before close the connection.