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.
Related
It's in the title, I want to create a program in C which connects to my MySQL database which is hosted locally with MAMP, I use as IDE CLion and I'm on Windows. I also use the MySQL API that I installed in my MinGW directory
So to do this I use this code:
#include <stdio.h>
#include <stdlib.h>
#include <winsock.h>
#include <MYSQL/mysql.h>
int main(int argc, char **argv)
{
printf("\nhello");
MYSQL *con = mysql_init(NULL);
if (con == NULL)
{
fprintf(stderr, "%s\n", mysql_error(con));
exit(1);
}
printf("\ntest");
if (mysql_real_connect(con, "localhost", "root", "root",
"perfect-concierge", 3307, NULL, 0) == NULL)
{
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
printf("\ntest2");
if (mysql_query(con, "CREATE DATABASE testdb"))
{
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
printf("\ntest3");
mysql_close(con);
exit(0);
}
"Tests" are there to see where there would be an error. And I use this CMakeFile.txt :
cmake_minimum_required(VERSION 3.12)
project(Test-MySQL C)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_FLAGS "-Wall")
add_library(libmysql SHARED IMPORTED)
set_target_properties(
libmysql
PROPERTIES LINKER_LANGUAGE C
IMPORTED_IMPLIB "C:/MinGW/lib/libmysqlclient.a")
link_directories("C:/MinGW/lib")
add_executable(Test-MySQL main.c)
target_link_libraries(Test-MySQL libmysql)
(PS : It is not me who made this CMakeFile but the one who gave me this example of connection to a MySQL database)
But when I execute this code the program compiles well, it runs then I get this error :
Process finished with exit code -1073741515 (0xC0000135)
Without anything else. I tried to just change the main function and just keep printf("\nhello"); and the program worked correctly, but just add MYSQL *con = mysql_init(NULL); send me this error again
Thank you in advance for the time you will take to help me.
The error
Process finished with exit code -1073741515 (0xC0000135)
means that some .dll cannot be found when the executable is run (at runtime).
On Windows you need either
Have directory with .dll (C:/MinGW/lib in your case) to be in your PATH variable.
Have .dll itself near the executable (at the same directory). See that question for the way how to achieve that in CMake.
Note, that link_directories (and similar) affects only on search the library during the linking stage and doesn't help at runtime.
MAMP is Macintosh, Apache, MySQL, Perl/Python/PHP. Which is the Apache as web server, MySQL as database server and Perl/Python/PHP as a module for the Web Server. Moreover, the important thing, MAMP is compatible in MacOS/Macintosh.
As your description, you are using Windows as the operating system, and C as your program language. So, for sure you can not use MAMP as your server.
Alternatively, You need to find any server that compatible for your Windows OS and your C as program language.
Hopefully it helps!
I am trying to configure C++ MySQL API in Xcode. I followed the instruction that the teacher provide us, first downloaded and installed the MySQL community server and Connector for C. I also edit Project setting:
Search Paths - Header Search Paths
/usr/local/mysql/include
Search Paths - Library Search Paths
/usr/local/mysql/lib
Linking - Other Linker Flags
-lmysqlclient
-lm
-lz
However, when I ran the code:
#include <mysql.h>
#include <iostream>
using namespace std;
int main (int argc, const char * argv[])
{
MYSQL *connection, mysql;
mysql_init(&mysql);
connection = mysql_real_connect(&mysql, "localhost", "root", "", "project3-nudb", 0, 0, 0);
if (connection == NULL)
{
//unable to connect
printf("Oh Noes!\n");
}
else
{
printf("You are now connected. Welcome!\n");
}
}
It kept showing "Oh Noes!\n" which indicate unable to connect. In the instruction slide, it also states:
In the terminal: (this step is important or the project can not find libmysqlclient.18.dylib)
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib
/usr/lib/libmysqlclient.18.dylib
I have tried the first line and don't quite know whats the second line mean. Since I look up the path /usr/lib/, there's no such file in the directory. I also tried to copy /usr/local/mysql/lib/libmysqlclient.18.dylib to /usr/lib/ but still not working.
Could someone tell me what step I got wrong? Thanks!
I'm having an absolute nightmare of a time trying to get the Sqlite C++ library to compile in Visual Studio 2013 Ultimate (Compiles fine in VS2012).
Basically regardless of whether I try to perform a clean or a rebuild VS will claim to successfully finish but will subsequently freeze and become unresponsive, never to recover.
Here is the output
and here is the actual VS project.
Anyone care to give it a crack and see if they are running into the same problem or provide any suggestions?
Tim Heuer gives step by step instructions ON THIS LINK. The batch files are hardcoded for TCL 8.5, you'll save yourself some time if you don't download the latest (8.6)
EDITED - I successfully compiled SQLite with Tim's steps (I just reinstalled Windows 8.1 / VS 2013). Note: the only issue I encountered was taking the steps to literally, be sure to change into the newly created SQLite directory before running the fossil command.
FYI for WinRT, be sure to use the correct path, if you just specify the filename you will get an access denied error (which will surface as a "cannot open database" error).
using namespace Windows::Storage;
using namespace std;
void SqliteWrapper::RunTest(void)
{
sqlite3 *db;
int rc;
auto path = ApplicationData::Current->LocalFolder->Path+"\\MyDatabase.db";
string dataPath(path->Begin(), path->End());
rc = sqlite3_open(dataPath.c_str(), &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
}
sqlite3_close(db);
}
i'm trying to install connection between c++ and mysql in ubuntu 12.04. i've installed mysql-client, mysql-server, libmysqlclient15-dev, libmysql++-dev. but when i try to compile the code i got the error: mysql.h there is no such file. i looked in the folders, there is mysql.h file, i can't understand why it can't find it. here is my code:
/* Simple C program that connects to MySQL Database server*/
#include <mysql.h>
#include <stdio.h>
main() {
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
char *server = "localhost";
char *user = "root";
//set the password for mysql server here
char *password = "*********"; /* set me first */
char *database = "Real_flights";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "show tables")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_use_result(conn);
/* output table name */
printf("MySQL Tables in mysql database:\n");
while ((row = mysql_fetch_row(res)) != NULL)
printf("%s \n", row[0]);
/* close connection */
mysql_free_result(res);
mysql_close(conn);
}
it's worked, but now i'm facing another error like :
mysql.c: In function ‘main’:
mysql.c:21: warning: incompatible implicit declaration of built-in function ‘exit’
mysql.c:27: warning: incompatible implicit declaration of built-in function ‘exit’
/tmp/ccinQBp8.o: In function `main':
mysql.c:(.text+0x3e): undefined reference to `mysql_init'
mysql.c:(.text+0x5e): undefined reference to `mysql_real_connect'
mysql.c:(.text+0x70): undefined reference to `mysql_error'
mysql.c:(.text+0xa5): undefined reference to `mysql_query'
mysql.c:(.text+0xb7): undefined reference to `mysql_error'
mysql.c:(.text+0xe7): undefined reference to `mysql_use_result'
mysql.c:(.text+0x11c): undefined reference to `mysql_fetch_row'
mysql.c:(.text+0x133): undefined reference to `mysql_free_result'
mysql.c:(.text+0x141): undefined reference to `mysql_close'
collect2: ld returned 1 exit status
The mysql.h file from the libmysqlclient-dev Ubuntu package is located at /usr/include/mysql/mysql.h.
This is not a standard search path for compilers, however /usr/include is.
You'd typically use the mysql.h header in your code like this:
#include <mysql/mysql.h>
If you don't want to specify the directory offset in your source, you can pass the -I flag to gcc (If that's what you are using) to specify an additional include search directory, and then you wouldn't need to change your existing code.
eg.
gcc -I/usr/include/mysql ...
just use
$ apt-get install libmysqlclient-dev
which will automatically pull the latest libmysqlclient18-dev
I have seen older versions of libmysqlclient-dev (like 15) puts the mysql.h in weird locations e.g. /usr/local/include etc.
otherwise, just do a
$ find /usr/ -name 'mysql.h'
and put the folder path of your mysql.h with -I flag in your make file. Not clean but will work.
For CentOS/RHEL:
yum install mysql-devel -y
this worked for me
$ gcc dbconnect.c -o dbconnect -lmysqlclient
$ ./dbconnect
-lmysqlclient is must.
and i would recommend to use following notation instead of using -I compilation flag.
#include <mysql/mysql.h>
You probably don't included the path to mysql headers, which can be found at /usr/include/mysql, on several unix systems I think. See this post, it may be helpfull.
By the way, related with the question of that guy above, about syntastic configuration. One can add the following to your ~/.vimrc:
let b:syntastic_c_cflags = '-I/usr/include/mysql'
and you can always check the wiki page of the developers on github. Enjoy!
You have to let the compiler know where the mysql.h file can be found. This can be done by giving the path to the header before compiling. In IDEs you have a setting where you can give these paths.
This link gives you more info on what options to use while compiling.
To your second problem
You need to link the libraries. The linker needs to know where the library files are which has the implementation for the mysql functions that you use.
This link gives you more info on how to link libraries.
I think you can try this gcc -I/usr/include/mysql *.c -L/usr/lib/mysql -lmysqlclient -o *
For those who are using Eclipse IDE.
After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,
You will need to tell Eclipse IDE about the following
Where to find mysql.h
Where to find libmysqlclient library
The path to search for libmysqlclient library
Here is how you go about it.
To Add mysql.h
1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql
To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.
2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient
3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.
Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql
This worked for me
yum install mysql
It will install mysql client and then
pip install mysqlclient
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