MySQL Connector C++ - make Error 1 - c++

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.

Related

Connecting mysql to C++ in VS Code, compiled succesfully but not running

I'm new to databases, so I wanted to make a program to perform simple queries in mysql with C++ in VS Code, in Windows 10. Last time I had problems with linking the library, and now it seems like I managed to fixed them. I have the following code taken from another source by adding my system configurations:
#include <iostream>
#include <windows.h>
#include "C:/Program Files/MySQL/MySQL Server 8.0/include/mysql.h"
int main(){
MYSQL* conn;
conn = mysql_init(0);
conn = mysql_real_connect(conn, "localhost", "root", "password", "project", 0, NULL, 0);
if(conn){
std::cout << "Connected" << std::endl;
} else {
std::cout << "Not connected" << std::endl;
}
}
When I compile it with the command g++ main.cpp -Wall -Werror -I "C:/Program Files/MySQL/MySQL Server 8.0/include" -L "C:/Program Files/MySQL/MySQL Server 8.0/lib" -lmysql, it compiles without reporting any errors. However, if I try to run it, the program simply terminates. I don't understand what problems could be. I suspect the problem might be with mysql connector, but as I said I'm new to it, so I still have doubts. So I would really appreciate it if you could help me out how I can proceed further.
I looked for similar questions, and they helped me only for linking to the library.
Fixed it. Just had to add libmysql.dll in a folder with the main.cpp file. Thank you all for your advices.
mysql_init can return NULL:
An initialized MYSQL* handler. NULL if there was insufficient memory to allocate a new object.
Wouldn't be safer to check its value before second call?

How to integrate MySQL with codeblocks IDE

I have been searching solution for this problem whole day.Any help would make me grateful. I am using Code::blocks IDE 16.01. I want to connect from my IDE to my MySQL database server. I have tried a lot of options but yet to succeed. I have my MYSQL INSTALLER setup already and have downloaded the mysql connector and mysql server. I am gonna show you the code and the way i have already tried.
This is my simple code
#include <iostream>
#include <windows.h>
#include <mysql.h>
using namespace std;
int main()
{
MYSQL* conn;
conn = mysql_init(NULL);
if (mysql_real_connect(conn,"localhost","root","","test",0,NULL,0) !=0)
{
cout << "Succesfully Connected to MySQL database xxxx" << endl;
}
mysql_close(conn);
return 0;
}
I have my MySQL setup in C drive and I have linked that as below
After doing all the work I have been shown the following errors
Please someone help me. Thanks in advance. Please feel free to ask If you guyz need anything to know.
In third step of your CodeBlocks setup you must specify the lib path (and not the include path), as below:
C:\Program Files\MySQL\MySQL Server 8.0\lib .
Then rebuilds your application.

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.

link libmysql.lib with gcc or dev c++ in windows

i've been trying to link mysql with c++ below is the code for ref
the file called sqlfunction.cpp has following code which helps connect mysql
#include <mysql.h>
#include "rlmodbusclient.h"
#include "modbusdaemon.h"
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
bool Opendb(char *pc,char *user, char *pass, char *db)
{
conn = mysql_init(NULL);
// Connect to database
if (!mysql_real_connect(conn, pc,
user, pass, db, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
return 0;
} else return 1;
}
now if above called from the program files like this
char pc[10]="localhost",user[5]="root",pass[8]="pass",db[6]="database";
ret = Opendb(pc,user,pass,db);
printf("opendb_buttonevent = %d\n",ret);
this is all good but the only thing is program is not compiling at all
the error is
undefined reference to mysql_init#4'
i found one solution for this which is
http://www.openwebspider.org/documentation/how-to-link-libmysqllib-with-dev-c-or-gcc-under-windows/
this link suggest to run reimp.exe with libmysql.lib
i tried to run this but this doesnt make any sense please if some one has done above then explain how to use reimp to solve this issue..
thanks
just like to add command which i'm using to run reimp
C:\Documents and Settings\XPMUser\Desktop\mingwutils\bin>reimp.exe "C:\Program F
iles\MySQL\MySQL Server 5.5\lib\libmysql.lib"
reimp.exe: dlltool: No such file or directory
as can be seen it says dlltool: no such file but i found that dlltool is part of
C:\MinGW\bin directory... which doesnt make any sense?????
The general problem is that the libmysql.lib library is in the Microsoft-specific lib format, which mingw cannot link against. It seems that reimp.exe can convert such libraries and needs dlltool to do so. It probably couldn't find it because it is not in your PATH. Try
set PATH=%PATH%;C:\MinGW\bin
reimp.exe "C:\Program Files\MySQL\MySQL Server 5.5\lib\libmysql.lib"
Afterwards, you should gain a libmysql.a file, which must be moved somewhere the mingw linker can find it, e.g. your project directory.

How to fix unresolved external symbol due to MySql Connector C++?

I followed this tutorial http://blog.ulf-wendel.de/?p=215#hello. I tried both on Visual C++ 2008 and Visual C++ 2010. Either static or dynamic, the compiler gave me the same exact error messages:
error LNK2001: unresolved external symbol _get_driver_instance
Has anyone experience this issue before?
Update:
+ Additional Dependencies: mysqlcppconn.lib
+ Additional Include Directories: C:\Program Files\MySQL\MySQL Connector C++ 1.0.5\include
+ Additional Libraries Directories: C:\Program Files\MySQL\MySQL Connector C++ 1.0.5\lib\opt
Another Update:
Click F12 on get_driver_instance() linked to:
class CPPCONN_PUBLIC_FUNC Driver
{
protected:
virtual ~Driver() {}
public:
// Attempts to make a database connection to the given URL.
virtual Connection * connect(const std::string& hostName, const std::string& userName, const std::string& password) = 0;
virtual Connection * connect(std::map< std::string, ConnectPropertyVal > & options) = 0;
virtual int getMajorVersion() = 0;
virtual int getMinorVersion() = 0;
virtual int getPatchVersion() = 0;
virtual const std::string & getName() = 0;
};
} /* namespace sql */
extern "C"
{
CPPCONN_PUBLIC_FUNC sql::Driver *get_driver_instance();
}
Apparently, the function existed, but the linker could not find it.
Code snippet:
#include <iostream>
#include <sstream>
#include <memory>
#include <string>
#include <stdexcept>
using namespace std;
#include "mysql_connection.h"
#include "mysql_driver.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
int main() {
try {
sql::Driver *driver;
sql::Connection *conn;
sql::Statement *stmt;
sql::ResultSet *res;
driver = get_driver_instance();
conn = driver->connect( "http://localhost/chandb", "root", "chan" );
stmt = conn->createStatement();
res = stmt->executeQuery( "select * from another" );
while( res->next() ) {
cout << "id = " << res->getInt( "Id" );
cout << "id = " << res->getInt( "GoldValue" );
cout << "id = " << res->getString( "Model" );
}
delete conn;
delete stmt;
delete res;
std::cout << "This is it";
}
catch( sql::SQLException e ) {
cout << e.what();
}
}
Thanks,
Chan
According to MySQL 5.1 Reference Manual if you are using the Version 1.1 of the MySQL Connector C++:
"get_driver_instance() is now only available in dynamic library builds - static builds do not
have this symbol. This was done to accommodate loading the DLL with LoadLibrary or dlopen. If you do not use CMake for building the source code you will need to define mysqlcppconn_EXPORTS if you are loading dynamically and want to use the get_driver_instance() entry point."
If I understand the previous note correctly, you have to use the dynamic build and define mysqlcppconn_EXPORTS.
If you use static linking, you need to set CPPCONN_PUBLIC_FUNC= in Project / Properties / C++ / Preprocessor / Preprocessor Definitions
I faced Same Error while using c++/Sql Connector.
and after spending entire day I solved this problem by using 32 bit libmysql.dll , 32 bit libmysqlcppcon.lib and 32 bit libmysqlcppcon.dll ( Dynamic binding is used because driver instance creation is only available in dynamic library of libmysqlcppcon.lib)
I found very good link explaining everything along with the working code. I think it would help others if they stuck at the same issue.
http://r3dux.org/2010/11/how-to-use-mysql-connectorc-to-connect-to-a-mysql-database-in-windows/
error LNK2001: unresolved external
symbol _get_driver_instance
That error message basically means that the linker cannot locate the function get_driver_instance anywhere, eg. it's not in any of the object files from your compilation units, not in a static .lib library or import library. This can also happen if the mangled names in the library doesn't match exactly with what the linker expects to find. eg. Library was built with different calling convention etc.
I would suggest that you take a look at the final command line being used from your project and update your post here for both compiling and linking. Second, make sure the mysql library you're linking against has that function. I believe there's a commandline tool in vs for dumping and viewing the contents of a static lib.
If you're linking against a dynamic dll version of mysql, make sure the import library contains the missing referenced symbol. Additionally, you can crack the dll open with a PE viewer and look under it's export tables to verify that that function actually exist and is visible.
Edit: According to this post, the function get_driver_instance should be in 'mysqlcppconn.lib' somewhere. Are you sure that file is being properly linked?
I read the article you mentioned.
It has this line for static compilation : As said, you need to link both "mysqlcppconn-static.lib" and "libmysql.lib".
Since you don't mention this is you question ,have you tried this ?
Also , on a forum I read this (for eclips) "You must have this in source":
#include "mysql_driver.h"
#include "mysql_connection.h"
using namespace sql::mysql;
Anyway ,good luck !
I don't know if you have your heart set on using this MySQL Connector/Driver package but there are many robust database wrappers available for free or nearly free out there if this is causing seemingly unspoken headaches for you.
I actually was thoroughly impressed by QT database objects when I used them previously for a data model project. The QT framework is licensed under LGPL and also has a commercial version available and is a very versatile set of cross platform libraries. The QtSql objects provide a consistent interface to many databases including MySql, SQLServer, Postgres, ODBC, etc with the ability to substitute your own drivers and still use the same interface for everything at a high level in C++
Some other notable options:
SQLApi++
MySQL++
Not trying to come on like a salesman or anything and I have no affiliation with any of these but sometimes it never hurts to shop around and find something that works better for your needs.
I solved using the 32bit version both for mysql server and connector/c++ on 64bit OS.
I think the problem are the boost libraries but im not sure.
I spent several hours trying to solve the problem exactly the same as you. I finally found out the problem myself. I downloaded the 64-bit version of MySQL/SQL Connector and followed a tutorial in MySQL.com in setting up win32 console project its properties and got the error message as mentioned. It was because the tutorial is teaching to build a 32-bit program. After I change to build a release version of X64 code, problem was solved.
Make sure your library is 32bit or 64bit and then configure your Visual Studio accordingly (in configuration manager).
Hello same problem for me, i have search and found my solution, i give you my paths on my local computer, but you can put all where you want, it's just my personnal notes:
The goal is to compile mysql cpp connector on your computer, to have lib which work on your computer when you compile somewhat with.
DEPENDENCIES:
clone (recursively with submodules, to have the folder jdbc) the repo on master branch (same than 8.0.27 for me when i write this post) of mysql cpp connector source code for windows on github:
https://github.com/mysql/mysql-connector-cpp/tree/master
Or if you haven't git, you can do it manualy by download zip: mysql-connector-c++-8.0.27-src.zip: https://dev.mysql.com/downloads/connector/cpp/
and download manualy jdbc by clicking on jdbc folder on this page: https://github.com/mysql/mysql-connector-cpp/tree/master
and the jdbc download must to be unzip and rename by "jdbc", and put in the mysql cpp connector folder
download mysql server for windows:
choice: Windows (x86, 64-bit), ZIP Archive
version: 8.0.27
size: 209.4M
url: https://dev.mysql.com/downloads/mysql/
filename: mysql-8.0.27-winx64
and put mysql-8.0.27-winx64 in C:\Users\< USER >\Downloads\mysql-8.0.27-winx64
download openssl (Win64 OpenSSL v1.1.1m):
binary installer msi: https://slproweb.com/products/Win32OpenSSL.html
it's not official :/ but that work (and it linked by this site too: https://wiki.openssl.org/index.php/Binaries), and i have failed and give up to build from source code)
Install openssl here: E:\OpenSSL-Win64
unfortunaly the version 3.0.1 doesn't work for build cpp connector (or my bad ?)
download boost: https://www.boost.org/users/download/
untarGz and put it here: E:\boost_1_78_0
CONFIGURATION:
for the configuration you must have this folder architecture:
. Parent Folder (for me it's E:\MySql)
|
|\
| \
| . _SOURCE (renamed mysql cpp connector repo)
| |
| .
| .
| .
| |
| |\
| | \
| | . jdbc (jdbc submodule)
| .
| .
| .
|
|\
| \
| . _BUILD
\
\
. _INSTALL
with this folder architecture if you have errors in next commands, your sources will not to be modify, you will have just to remove the containt of _BUILD and _INSTALL folders to relaunch
open powershell in E:\MySql and launch cmd:
cmake .\_SOURCE\ -B .\_BUILD\ -D CMAKE_INSTALL_PREFIX=.\_INSTALL -D CMAKE_BUILD_TYPE=Debug -D WITH_SSL="E:\OpenSSL-Win64" -D BUILD_STATIC=OFF -D WITH_JDBC=ON -D WITH_MYSQL="C:\Users\< USER >\Downloads\mysql-8.0.27-winx64" -D WITH_BOOST="E:\boost_1_78_0" -D MYSQLCLIENT_STATIC_BINDING=OFF -D MYSQLCLIENT_STATIC_LINKING=OFF -G "Visual Studio 16" -A "x64"
the last lines of output must to be like:
-- Configuring done
-- Generating done
-- Build files have been written to: Your-Build-Path/_BUILD
BUILDING:
launch cmd: cmake --build .\_BUILD\
There are a lot of fatal errors possible:
mysql not found
boost not found
openssl not found
openssl bad version (need 1.1.1)
no compatible options values between options
forgoten options, if this is the case, try to add the option with his default value
so check yours paths dependecies if you have errors
There somes not fatal warning:
the "is_same" test doesn't work
file sys/endiand.h not found
file sys/byteorder.h not found
when the output say "look log files output.log and errors.log" you have fatal error some where, but may be (MAY BE) don't loss time on the warnings and on the logs files... and look all the lines of the ouput, because for me the fatals errors was not listed in the logs files but in the output (may be not for you, i don't know)
INSTALLATION:
cmake --install .\_BUILD\ --config Debug
END:
in folder: E:\MYSQL\_INSTALL\lib64
there are dynamic lib
in folder: E:\MYSQL\_INSTALL\lib64\vs14
there are static lib
and E:\MYSQL\_INSTALL\lib64\vs14\mysqlcppconn.lib
will containt "get_driver_instance" functions to use mysql cpp connector etc...
if you want open mysqlcppconn.lib with 7zip, right click, open archive, open 1.txt and 2.txt, and CTRL+F your functions
NOTES:
you can't configurate in Debug (-D CMAKE_BUILD_TYPE=Release), else the first cmake cmd will create a visual studio project (E:\MYSQL\_BUILD\jdbc\connector-jdbc-deps.vcxproj) with inside a unknow linked library (MYSQLLIB-NOTFOUND-DEBUG), and the cmake build cmd will fail
in my visual studio project, i have link the two static lib, and i have copy past the two dynamic lib next to my exe, that work for me
VERSION-ARCH:
software
version
arch
windows pro
10
x64
cmake
3.22.1
x64
Microsoft Visual Studio Community 2019
16.11.8
x64
Microsoft .NET Framework
4.8.04084
x64
openssl
v1.1.1m
x64
boost
1.78.0
cross-arch ?
mysql server
8.0.27
x64
mysql cpp connector
8.0.27
x64