How To Connect SQLite with C++? - c++

Can someone please tell me how do i make SQLite to connect with my C++ program.
I am a complete beginner in programming and is trying to make a very basic project on a banking system.
I thought of storing the transactions made by the account holders in a sql database and came across sqlite.
Then i tried to look for how to connect the two but could not find anything.
Dissapointed i tried doing sommething like this:
ofstream fout;
fout.open("crtab.sql", ios_base::ate);
fout << ".open test.db" << endl <<"CREATE TABLE " << name << "(id integer);" << endl << ".exit";
fout.close();
system("sqlite3.exe crtab.sql");
cout << "Database Updated";
`
This did not work either.
My teacher suggests me to store the data in a text file but i think it's a stupid idea.
My Operating System is Windows 10 and ide is dev-c++ with TDM-GCC 4.9.2
I also have Visual Studio 2017 Community installed.
Which one should i use??
Please help quick.

SQLite Databases are stored in files, so you just need to open them. But you can't just use fopen or streams, you have to use the appropiate function that SQLite provides, which seems to be this one.

Finally got it working.
First I downloaded the sqlite-amalgamation zip. Then i extracted the files sqlite3.h and sqlite3.c and fnally i used gcc like this
gcc main.cpp sqlite3.c
This got the the test program to work.
Thanks to all the helpers...

Related

std::ifstream::open() fails in Windows 10 Universal apps

I'm working on a Windows 10 Universal C++ project and I'm trying to open a binary file in read-mode using std::ifstream.
This is my code:
std::ifstream imgFile("C:\\Users\\GuiTeK\\Desktop\\picture.bmp", std::ios::binary);
if (imgFile.is_open())
{
std::cout << "OK" << std::endl;
}
else
{
int error = errno;
std::cerr << "KO: " << error << std::endl;
}
Problem is that it keeps failing with error 13, which means "The data is invalid" (C.F. System Error Codes).
However, the exact same code works fine in a Win32 Console Application C++ project.
What's wrong?
UWP apps do not have permission to access all files on the device. By default, apps can access certain file system locations such as application install directory or application data locations. For more info, please see File access permissions.
"C:\Users\GuiTeK\Desktop\picture.bmp" is a location that you app can't directly access. In UWP, we will need a File​Open​Picker to access such a file. One important rule here is that Skip the path: stick to the StorageFile.
For more info about how to handle files in UWP, please see Files, folders, and libraries and also File access sample, File picker sample on GitHub.

Xcode App No Longer Reads Input From the Folder The App is Stored In

The title is a bit long-winded, but basically, I've written an app that reads and writes its input and output to text files. The entire time, it would read and write the files directly in the same directory as my Xcode derived data->project->build->products->debug folder. This was where everything was being written to and read from. I don't have a custom path set up for the application, so it just saves wherever the app is located. For the first time ever, I ran Apple's Instruments app, to try to learn how to use a profiler. Not long after selecting this app as the target in Instruments, I went back to the Xcode app to run the program some more. Everything works fine in Xcode. It reads from the files and prints to files in the same location as the folder, but if I try to run the actual program itself by clicking on the file and having it open terminal, it no longer reads or prints to the directory that app is in. Instead, its printing and reading from my home folder. I don't know what changed or what caused it to change, but I'm hoping its a simple fix. I'd like for the application to read from files and print files from the directory its located in again. I'm not sure if its an Xcode setting or a Terminal setting.
Any help would be greatly appreciated.
Update 1: Tried this with no luck:
how to change the working directory to the location of the program
The directory field was blank, so I thought this would the solution, but filling it in with the suggestion did nothing to alleviate the issue.
Update 2:
Just tried deleting the preference file, still no solution. I'm willing to give someone reputation. I don't have a whole lot because I'm a newer member, but I'll give what the person thinks is fair, to whoever solves it. I'm desperate and really don't want to wait 2 days to have this issue solved.
Update 3:
Tried changing the default path in the "Profile (release)->options area in the scheme section to the default variable suggested in update 1. No luck. I'm beginning to lose my mind.
Update 4:
I've tried deleting the scheme entirely and making a new one, in hopes that maybe there was something botched with the scheme, but this did not solve the issue. Input and output while running the app in Xcode is still using the working directory, while running the executable in the debug folder is using the home folder.
Update 5:
Just tested this on an older iMac and Xcode setup (OS 10.8.5 and Xcode 5.1.1) and it seems to be working correctly, reading and writing to the current working directory of the application in the debug folder.
For whatever reason, the solution suggested by https://stackoverflow.com/a/15537436/1035008 no longer works. Maybe broken in Xcode 8.1. But this seems to work:
#include <iostream>
#include <fstream>
#include <unistd.h>
using namespace std;
int main (int argc, const char * argv[])
{
// argv[0] returns the full path to the program, in my case "/Users/yuchen/Library/Developer/Xcode/DerivedData/../Debug/test
string directory(argv[0]);
// And we want to get rid of the program name `test`
directory = directory.substr(0, directory.find_last_of("/"));
// Point the directory to the program directory
chdir(directory.c_str());
cout << "Current directory is: " << getcwd(NULL, 0) << endl; // /Users/yuchen/Library/Developer/Xcode/DerivedData/../Debug/
ifstream fin("hi.txt");
if (fin.is_open()) cout << "File is Open" << endl;
else cout << "File is not open" << endl;
fin.close();
return 0;
}
Also see SO and SO. Hope this helps.

Variant on: New to Xcode can't open files in c++?

Like the questioner in "New to Xcode can't open files in c++?" I'm learning Xcode and OS X (I'm using Xcode 7 on a Yosemite mac).
I can get the code to work perfectly when I build and run it, but can't get the executable to work when I try to run it as a stand alone program.
I'm trying to translate some games I've written on a PC in C++ using SFML.
There has to be a way to save high scores and previous games within an app, but this has me stymied.
This is the sample code I used based on the previous question:
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
string input;
fin.open("inputFile.txt");
if(fin.fail())
cout << "File failed to open." << endl;
fin >> input;
fin.close();
fout.open("outputFile.txt");
fout << input;
fout << "\n Data transferred \n";
fout.close();
}
This works perfectly when I build and run it, so I've got the proper path to the desktop folder set up. (I'm putting the data files in the same folder as the executable and specifying the path in Xcode.)
No problems when I run this within Xcode, but this is the message on the terminal console when I run the executable by itself:
"…/Desktop/datafiles/Build/Products/Debug/datafiles ; exit;
…/Desktop/datafiles/Build/Products/Debug/datafiles ; exit;
File failed to open.
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[Process completed]"
Is there another flag or path that needs to be set within Xcode for this to work? Two other related questions: How do I access the terminal history to see what is going on? Finally, if I set up the project as an SFML app instead of a terminal project (command line tool app), why can't I see the files within the SFML app, even though I've set the command line flag to see hidden files, and I can see other hidden files on my hard drive? I can see the files if I open the SFML app folder in Windows, so I know they are there.
This is my first question on Stack Overflow, so apologies if this should be appended to the previous question, but this doesn't appear to be an answer to me, but is quite a different version of the original question that is not addressed in the answers.
Thanks!

How to connect mySQL database using C++

I'm trying to connect the database from my website and display some rows using C++.
So bascily I'm trying to make an application that does a select query from a table from my site database. Now, this must be possible because I've seen tons of applications doing it.
How do I do this? Can some one make an example and tell me what libraries I should be using?
Found here:
/* Standard C++ includes */
#include <stdlib.h>
#include <iostream>
/*
Include directly the different
headers from cppconn/ and mysql_driver.h + mysql_util.h
(and mysql_connection.h). This will reduce your build time!
*/
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
cout << endl;
cout << "Running 'SELECT 'Hello World!' »
AS _message'..." << endl;
try {
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
/* Create a connection */
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
/* Connect to the MySQL test database */
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
while (res->next()) {
cout << "\t... MySQL replies: ";
/* Access column data by alias or column name */
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
/* Access column fata by numeric offset, 1 is the first column */
cout << res->getString(1) << endl;
}
delete res;
delete stmt;
delete con;
} catch (sql::SQLException &e) {
cout << "# ERR: SQLException in " << __FILE__;
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
cout << "# ERR: " << e.what();
cout << " (MySQL error code: " << e.getErrorCode();
cout << ", SQLState: " << e.getSQLState() << " )" << endl;
}
cout << endl;
return EXIT_SUCCESS;
}
Finally I could successfully compile a program with C++ connector in Ubuntu 12.04
I have installed the connector using this command
'apt-get install libmysqlcppconn-dev'
Initially I faced the same problem with "undefined reference to `get_driver_instance' " to solve this I declare my driver instance variable of MySQL_Driver type. For ready reference this type is defined in mysql_driver.h file. Here is the code snippet I used in my program.
sql::mysql::MySQL_Driver *driver;
try {
driver = sql::mysql::get_driver_instance();
}
and I compiled the program with -l mysqlcppconn linker option
and don't forget to include this header
#include "mysql_driver.h"
Yes, you will need the mysql c++ connector library. Read on below, where I explain how to get the example given by mysql developers to work.
Note(and solution): IDE: I tried using Visual Studio 2010, but just a few sconds ago got this all to work, it seems like I missed it in the manual, but it suggests to use Visual Studio 2008. I downloaded and installed VS2008 Express for c++, followed the steps in chapter 5 of manual and errors are gone! It works. I'm happy, problem solved. Except for the one on how to get it to work on newer versions of visual studio. You should try the mysql for visual studio addon which maybe will get vs2010 or higher to connect successfully. It can be downloaded from mysql website
Whilst trying to get the example mentioned above to work, I find myself here from difficulties due to changes to the mysql dev website. I apologise for writing this as an answer, since I can't comment yet, and will edit this as I discover what to do and find the solution, so that future developers can be helped.(Since this has gotten so big it wouldn't have fitted as a comment anyways, haha)
#hd1 link to "an example" no longer works. Following the link, one will end up at the page which gives you link to the main manual. The main manual is a good reference, but seems to be quite old and outdated, and difficult for new developers, since we have no experience especially if we missing a certain file, and then what to add.
#hd1's link has moved, and can be found with a quick search by removing the url components, keeping just the article name, here it is anyways: http://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-complete-example-1.html
Getting 7.5 MySQL Connector/C++ Complete Example 1 to work
Downloads:
-Get the mysql c++ connector, even though it is bigger choose the installer package, not the zip.
-Get the boost libraries from boost.org, since boost is used in connection.h and mysql_connection.h from the mysql c++ connector
Now proceed:
-Install the connector to your c drive, then go to your mysql server install folder/lib and copy all libmysql files, and paste in your connector install folder/lib/opt
-Extract the boost library to your c drive
Next:
It is alright to copy the code as it is from the example(linked above, and ofcourse into a new c++ project). You will notice errors:
-First: change
cout << "(" << __FUNCTION__ << ") on line " »
<< __LINE__ << endl;
to
cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
Not sure what that tiny double arrow is for, but I don't think it is part of c++
-Second: Fix other errors of them by reading Chapter 5 of the sql manual, note my paragraph regarding chapter 5 below
[Note 1]: Chapter 5 Building MySQL Connector/C++ Windows Applications with Microsoft Visual Studio
If you follow this chapter, using latest c++ connecter, you will likely see that what is in your connector folder and what is shown in the images are quite different. Whether you look in the mysql server installation include and lib folders or in the mysql c++ connector folders' include and lib folders, it will not match perfectly unless they update the manual, or you had a magic download, but for me they don't match with a connector download initiated March 2014.
Just follow that chapter 5,
-But for c/c++, General, Additional Include Directories include the "include" folder from the connector you installed, not server install folder
-While doing the above, also include your boost folder see note 2 below
-And for the Linker, General.. etc use the opt folder from connector/lib/opt
*[Note 2]*A second include needs to happen, you need to include from the boost library variant.hpp,
this is done the same as above, add the main folder you extracted from the boost zip download, not boost or lib or the subfolder "variant" found in boostmainfolder/boost.. Just the main folder as the second include
Next:
What is next I think is the Static Build, well it is what I did anyways. Follow it.
Then build/compile. LNK errors show up(Edit: Gone after changing ide to visual studio 2008). I think it is because I should build connector myself(if you do this in visual studio 2010 then link errors should disappear), but been working on trying to get this to work since Thursday, will see if I have the motivation to see this through after a good night sleep(and did and now finished :) ).
I had to include -lmysqlcppconn to my build in order to get it to work.

How to launch the associated application for a file / directory / URL?

Linux seems to be easy: xdg-open <file/directory/URL>.
Apparently, Mac is similar: open should be used instead of xdg-open. I don't have access to a Mac so I couldn't test it.
For Windows, I found 4 different suggestions and those that I have tried failed.
Is there a non-java, cross platform way to launch the associated application for a certain file type?
suggests start
How to give focus to default program of shell-opened file, from Java? suggests
cmd /c start ...
How to open user system preferred editor for given file?
How to Find Out Default File Opener with Java?
suggest RUNDLL32.exe
What is the correct way to use ShellExecute() in C to open a .txt
Open file with Windows' native program within C++ code
How to use ShellExecute to open html files in Windows using C++? suggest
ShellExecute
I have tried the first 3 with system() and QProcess::startDetached() and "http://www.stackoverflow.com" as argument but they all failed; start works just fine from the command line though. I haven't tried ShellExecute yet.
What is the Windows equivalent of xdg-open? It seem to me, it is start but why did my attempts with start fail?
Is ShellExecute my only option?
EDIT I thought QDesktopServices::openUrl() was for web pages only because it did not work for files or directories.
After some debugging I figured out that if I replace \\ with / in the path on Windows, it works for files but the directories are still not opened. Any ideas what I am doing wrong?
QDir dir("C:/Documents and Settings/ali");
qDebug() << "Exists? " << dir.exists();
qDebug() << dir.absolutePath();
QDesktopServices::openUrl(QUrl(dir.absolutePath()));
qDebug() << "External app called";
Application Output:
Exists? true
"C:/Documents and Settings/ali"
External app called
But nothing happens, the directory is not opened. On Linux, directories are opened with the default file manager as expected.
SOLUTION: Due to the Qt bug and Windows quirks (malformed application window), I ended up using ShellExecute. That gives me enough flexibility to achieve exactly what I want at some expense...
Why don't you just use Qt's support for this? For example:
QDesktopServices::openUrl(QUrl("/home/realnc/test.pdf"));
This opens the document in Acrobat Reader. In general, it obeys the preferred application settings in my OS for all file types that have one or more applications associated with them. Best of all, it's platform-independent.
Edit:
The fact that it opens directories on Linux but not on Windows smells like a bug. It might be best to report this on Qt's bug tracker. In the meantime, you could have a workaround for Windows for when the file is a directory:
#ifdef Q_WS_WIN
if (QFileInfo(path).isDir())
QProcess::startDetached("explorer", QStringList(path));
else
#endif
QDesktopServices::openUrl(QUrl(path));
You can also do it with cmd.exe's start command, but you'll get an ugly terminal pop up for a few fractions of a second:
QProcess::startDetached("cmd", QStringList() << "/C" << "start"
<< QDir::toNativeSeparators(path));