Professional Documents
Culture Documents
C++ is a very good programming language with high-level and low-level capabilities.
Linux is a Unix-like computer operating system. It promotes community of free and open source
software. Almost using those instruments it is possible to make a complex and sophisticate
enterprise system.
In this article is shown how to connect to a MySQL database using C++ under a Linux operating
system.
#include <sys/time.h>
#include <stdio.h>
#include <mysql.h>
// code
return 0;
};
MYSQL_RES *result;
MYSQL_ROW row;
int state;
Of course if we want to use MySQL database, we must connect to it, using the next code:
mysql_init(&mysql);
connection = mysql_real_connect(&mysql,host,usr,pswd,database,0,0,0);
Where
host – is a host name, the location of the MySQL database server, for example “localhost” or
“remotehost.com”
If something goes wrong, for example password is not right, we must know it, and display the
error message:
if (connection == NULL)
printf(mysql_error(&mysql));
return 1;
Now we make a simple query like “SELECT * FROM mytable” and check if it has no errors, where
“mytable” is the name of wished table:
if (state !=0)
printf(mysql_error(connection));
return 1;
After the successful execution of the query, we must store the results somewhere:
result = mysql_store_result(connection);
printf(“Rows:%d\n”,mysql_num_rows(result));
Using while statement and mysql_fetch_row functions, it possible to process each row in the
result set:
{
printf(” %s, %s\n”, (row[0] ? row[0] : “NULL”), (row[1] ? row[1] : “NULL” ));
mysql_free_result(result);
mysql_close(connection);
Enjoy!
« Previous Next »
Leave a comment
Reply
Hi
I get this ERROR:
`MYSQL_RES’ undeclared (first use this function)
What wrong?
HELP
Contact me on stian.instebo@gmail.com
Reply
A programmer on October 14, 2008 at 6:32 am
Reply
Reply
Hy. I`ve read your example code and I tried to create a .cpp file with. When I try to compile
it says that MYSQL/MYSQL_RES/MYSQL_ROW was not declared in this scope.
I tried to change the include line from #inlcude to #include but no good results.
Reply
Reply
thanks man!
i will try your code
Reply
righteous on July 18, 2009 at 1:18 pm
Good, but this is the C API. You should be using the Connecter C++ API from MySQL
http://codediaries.blogspot.com/2009/07/mysql-connector-c-example-windows-
clexe.html
Reply
It’s worth mentioning when using your IDE you can also add the mysqlclient to the
libraries list.
Reply
Thanks man!
Reply
Hi , good post .
only tht you used the SQL c API .
there is also a C++ only Connector which is object oriented
that worth a mention.
http://www.mysql.com/downloads/connector/cpp/
Reply
Hi Vladimir,
Thank you, working perfectly here, I used a slightly different compile command as the
one given gave some problems on my linux box, the compile command for anyone else
to try: g++ test.cpp -I/usr/include/mysql -L/usr/lib/mysql -lmysqlclient_r -o test
Reply
Blog at WordPress.com.