How to connect mySQL database using C++ - 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.

Related

How to run SSH with system() in C++

I've written a simple program to connect to a Linux server using SSH via my C++ program. Here's the code:
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int main()
{
string hostIP;
string username;
string password;
cout << "Welcome to SSH Program" << endl;
cout << "----------------------" << endl;
cout << "\nEnter host ip or name Example: \"capa.its.uow.edu.au\": ";
cin >> hostIP;
cout << "Enter username: ";
cin >> username;
cout << "\nConnecting...\n" << endl;
string composite = "ssh " + username + "#" + hostIP;
char command[100];
strcpy(command, composite.c_str());
system(command);
system("pause");
}
It runs well on Ubuntu, but when I compile this same code on Visual Studio in Windows and execute it, the console present me with this error: 'ssh.exe' is not recognized as an internal or external command, operable program or batch file.
This didn't make sense to me because OpenSSH Client is clearly installed on my computer and I'm able to establish an SSH connection if I directly enter ssh username#server.ip.address in the command prompt.
I thought it might be an issue with the environment paths and so in Visual Studio, I checked Project>Properties>VC++ Directories>Executable Directories. There I found C:\WINDOWS\System32\OpenSSH\ among other paths, located in the Evaluated value: box.
Doesn't this mean everything should run fine since the OpenSSH directory is located in the path? Also, like I said, I am able to connect via SSH if I enter the command directly into the command prompt instead of the program.
Please help. I've been really scratching my head over this since last night.
I've managed to solve this issue. It seems to have been a problem with the selected platform in Visual Studio. Initially the platform for the project was set for an x86 architecture. This is the reason why ssh.exe could not be accessed even though it was present in the environment path.
By changing the platform to 64-bit architecture in the project properties, the program could reference the correct environment variables and execute ssh.exe as intended.

How To Connect SQLite with 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...

{c++} programs send error 0xc00007b when run on a computer without visual studios proper dlls are in place

I have this program:
#include <iostream>
#include <string>
using namespace std;
int main() {
string inputfile = "input.pdf";
string outputfile = "output.tiff";
cout << "paste path of pdf to convert" << endl;
getline(cin, inputfile);
cout << "type the path of the output file with the correct extension ie png jpeg or tif" << endl;
getline(cin, outputfile);
string command = "gm.exe montage -tile 1x10000 -geometry 85% -density 150x150 " + inputfile + " -quality 100 " + outputfile;
system(command.c_str());
return 0;
}
As you can see its using the std library. I did not use a setup project because it felt unnecessary as A could easily just copy and paste the application and the dlls. Before I included dlls in the copy it gave me the following error message:
MSVCP140d.dll is missing and the program cant start.
I got a copy of the DLL from my computer and that seemed to solve the issue, but then when I ran it on the non development computer it gave me:
ucrtbassed.dll is missing and the program cant start.
I downloaded the missing DLL from the internet, but now when I go to launch the program I get this error:
The application was unable to start correctly (0xc0000007b}. Click OK to close the application.
It seems that when a computer has Visual Studio installed the code runs fine; however, when they don't have Visual Studio installed it doesn't run. I have installed the VCredist.exe and the same problem happens.
regards Shrimp
Build you project Release version. Not the Debug. Symbol d at the end of .dll name shows that you have built debug version.
Link all libraries statically right clink on Project -> Properties (-> select Release configuration and All Platforms at top of the window) -> C/C++ -> Code Generation -> set "Runtime Library" to "Multi-threaded (/MT)"
Don't forget to escape arguments you pass to command line for other app. I fixed one line of your code. See additional quotes around file names.
string command = (string)"gm.exe montage -tile 1x10000 -geometry 85% -density 150x150 " +
"\"" + inputfile + "\" -quality 100 \"" + outputfile + "\"";

how to change the working directory to the location of the program

I want to use c++ to open a file on Mac OS.
If I run the program under Xcode, the working directory is the same with the program, which is fine. However, if I try to run the program in terminal, the working directory is alway "Users/username". Do you know how to change the working directory to the location of the program?
Here is the sample code:
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, const char * argv[])
{
char * dir = getcwd(NULL, 0);
cout << "Current dir: " << dir << endl;
ifstream fin("hi.txt");
if (fin.is_open()) cout << "File is Open" << endl;
else cout << "File is not open" << endl;
fin.close();
return 0;
}
Use the value $(PROJECT_DIR) in the working directory in your scheme debug settings:
You can set a custom working directory for your project in Xcode. In Xcode 4 choose Edit Scheme from the Scheme menu in the project window toolbar to open the scheme editor. Select the Run step from the left side of the project editor. Click the Options button at the top of the scheme editor. Select the Use custom working directory checkbox. Click the button on the right side of the text field to choose the working directory.
This is a really old post - updating some info for Xcode 12 (Sept 2020)
Step 1). Xcode -> Product -> Scheme -> Edit Scheme (or create a new one)
Step 2) RUN(DEBUG), Working Directory(Checkmark) and enter $(PROJECT_DIR) as a starting point.
You could use chdir(), see here: Change the current working directory in C++.
Or if you could always just issue a system call (stdlib.h): http://www.cplusplus.com/reference/clibrary/cstdlib/system/. This won't be portable, but it might be good enough for what you need.

MySQL Connector C++ - make Error 1

I'm writing an application in C++ (using Eclipse with Linux GCC) that's supposed to interact with my MySQL server.
I've downloaded the MySQL Connector C++ a, precompiled, and copied the files into the directories (/usr/lib, /usr/include). I've referenced in in the GCC C++ Linker Section of the Project Properties in Eclipse ( "mysqlcppconn"). My code comes directly from the MySQL Reference (Hello World) except I removed error handling and the delete statements at the end (I'm not even getting there so whats the point)
#include <stdlib.h>
#include <iostream>
#include "mysql_connection.h"
#include "mysql_driver.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
sql::Driver *driver;
sql::Connection *con;
sql::Statement *stmt;
sql::ResultSet *res;
driver = get_driver_instance();
con = driver->connect("tcp://127.0.0.1:3306", "root", "root");
con->setSchema("test");
stmt = con->createStatement();
res = stmt->executeQuery("SELECT 'Hello World!' AS _message");
while (res->next())
{
cout << "\t... MySQL replies: ";
cout << res->getString("_message") << endl;
cout << "\t... MySQL says it again: ";
cout << res->getString(1) << endl;
}
return EXIT_SUCCESS;
}
now when I compile this, It gives me a make error 1, which the man page says means I need to recompile my packages. I've tried it, it doesn't work.
I seem to have hit dead ends everywhere. Can anyone tell me how to fix this problem? (make could really tell me what I should recompile.) Anyone have any tips/suggestions/ideas where I went wrong?
Edit - Chagned the code a bit, but the general idea is the same.
Update - If I use the terminal instead of exlipse to make, it tells me that the problem is obviously that the connector wants libstdc++.so.5 whilst I have libstdc++.so.6.
The Solution is quite simple - compile your own Connector. I did it with the 1.0.5 version of the Connector. to do it, you need to install the package via
sudo apt-get install mysql-client
In the directory of the source package you downloaded (and extracted), type
cmake .
apparently, in three files of the driver, references are made to snprintf and printf, without including the stdio.h header. I added
#include <stdio.h>
to each file and then, in the terminal, typed
make
then, I copied the Files to my lib directory
sudo cp path/to/driver/libmysqlcppconn* /usr/lib/
and everythign worked a charm.
Download and install the C++ MySQL development packages for your distribution. For ubuntu, run # sudo apt-get install libmysql++-dev.