48

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?

lepel100
  • 579
  • 1
  • 5
  • 11

4 Answers4

41

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;
}
hd1
  • 33,938
  • 5
  • 80
  • 91
  • 7
    Do I need libarys for that? And is that secure? Because some one said you should never store passwords in a file. – lepel100 May 07 '13 at 17:17
  • Given that it's a source file that will be compiled into a binary, which is (presumably) going to be distributed, it's reasonably secure. Also, you'll need the mysql library, detailed on the linked page. – hd1 May 07 '13 at 17:19
  • 11
    It's not secure. It's easy to extract all strings from a binary to get the password. And a more knowledgeable assailant can see where you call `driver_connect()` and just follow that back to the password in the binary. But this is not the level at which security should happen. The *server* is the only one who can enforce security. You should create separate accounts for everyone, and instead ask for username and password at startup. If that's not an option, limit access of the user to either be read-only, or create your own server process that only supports the tasks that should be permitted. – uliwitness Nov 25 '14 at 07:24
  • Balderdash, @uliwitness, if you compile without debug symbols, strings (or equivalent) won't work on the binaries. – hd1 Nov 25 '14 at 07:37
  • 2
    @hd1 It will for string constants & other data section contents, which the password in the example above falls under. You might not get `driver_connect()` itself if you statically link it, but at some point you'll be calling into a system dylib, and it's fairly easy to backtrack from a call to e.g. `connect()` on a socket. The matter of the fact is: If the computer can extract the password to give it to `driver_connect()`, so can the user of the computer. So if one of your users is malicious or compromised, this approach is not secure. That's why you need per-user passwords. Limit the damage. – uliwitness Nov 25 '14 at 07:54
  • 10
    All that buzz only because of an example, i'm pretty sure nobody building a good app will embed access login info on it's code. – Frederic Yesid Peña Sánchez Jan 28 '15 at 15:30
  • @hd1 the link is dead can you provide an alternative please? – Cfun Aug 17 '16 at 21:04
  • My solution was encrypting the username and password even the connection details into a file then decrypt them back using a function I made at the Startup of my game. Anyone can see the string constants and that's right using any software like HxD. I used XOR operator in my algorithm so I can use just one function for both decrypting/encrypting with a numeric **key** so they cannot see it bc it's not a string constant. So let's assume somehow (impossible) But let's say they got that numeric key which is the decryption password, they'd never know how my complicated algorithm works to use it. – Beyondo Jun 05 '18 at 00:07
  • Note that the need to include the header files isn't to speed up compilation; but the root one only has forward declarations; meaning that, for example, no functions can be called on the statement. On the up side, it means that there's no significant cost in including the top include in header files that will hold any precompiled statements – UKMonkey Jun 13 '18 at 08:47
  • The connector was updated, [dev.mysql.com/doc/dev/connector-cpp/8.0](https://dev.mysql.com/doc/dev/connector-cpp/8.0/) –  Mar 24 '19 at 02:45
  • it works but I had to add -l mysqlcppconn option to my compiler command – clay Aug 25 '23 at 18:39
12

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" 
munawwerali
  • 167
  • 2
  • 12
7

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

Alan Ball
  • 593
  • 8
  • 17
4

I had to include -lmysqlcppconn to my build in order to get it to work.

Nick Kotenberg
  • 914
  • 9
  • 8