Howto: Connect MySQL server using C program API under Linux or UNIX
From my mailbag:
How do I write a C program to connect MySQL database server?
The C API code is distributed with MySQL. It is included in the mysqlclient library and allows C programs to access a database.
Many of the clients in the MySQL source distribution are written in C. If you are looking for examples that demonstrate how to use the C API, take a look at these clients. You can find these in the clients directory in the MySQL source distribution.
Requirements
Make sure you have development environment installed such as gcc, mysql development package etc. Following is the list summarize the list of packages to compile program:
- mysql: MySQL client programs and shared library
- mysqlclient: Backlevel MySQL shared libraries (old libs)
- mysql-devel: Files for development of MySQL applications (a must have)
- mysql-server: Mysql server itself
- gcc, make and other development libs: GNU C compiler
Sample C Program
Following instructions should work on any Linux distro or UNIX computer. Here is the small program that connects to mysql server and list tables from mysql database.(download link):
/* Simple C program that connects to MySQL Database server*/ #include#include main() { MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; char *server = "localhost"; char *user = "root"; char *password = "PASSWORD"; /* set me first */ char *database = "mysql"; 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); }
How do I compile and link program against MySQL libs?
MySQL comes with a special script called mysql_config. It provides you with useful information for compiling your MySQL client and connecting it to MySQL database server. You need to use following two options.
Pass --libs option - Libraries and options required to link with the MySQL client library.
Pass --libs option - Libraries and options required to link with the MySQL client library.
$ mysql_config --libsOutput:
-L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto
Pass --cflags option - Compiler flags to find include files and critical compiler flags and defines used when compiling the libmysqlclient library.
Output:
$ mysql_config --cflagsOutput:
-I/usr/include/mysql -g -pipe -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing
You need to pass above option to GNU C compiler i.e. gcc. So to compile above program, enter:
Now execute program:
Output:
$ gcc -o output-file $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs)Now execute program:
$ ./output-fileOutput:
MySQL Tables in mysql database: columns_priv db func help_category help_keyword help_relation help_topic host tables_priv time_zone time_zone_leap_second time_zone_name time_zone_transition time_zone_transition_type user
References:
- MySQL C API - A must read - official MySQL C API documentation
Featured Articles:
- 30 Cool Open Source Software I Discovered in 2013
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop
Tagged as: c api, c program, development libs, gcc, gnu c compiler, linux c connect mysql, mysql client, mysql database server, mysql development, shared library
PREVIOUS POST: nixCraft FAQ Roundup May 29, 2007
I have used this code and copy it to the PCW program to connect to mysql but it gives me this error.. a #Device required before this line….it is in string.h
Please anyone can help me
Thank you ^.^
MYSQLLIBS=`mysql_config –libs`
datafoxclient:
$(CC) -I/usr/include/mysql -o datafoxclient $(MYSQLCFLAGS) datafoxclient.c $(MYSQLLIBS)
clean:
rm -f datafoxclient
code add/edit/delete bla bla bla etc ?
plz anyone help me
“error while loading shared libraries: libmysqlclient.so.15: cannot open shared object file: No such file or directory”
Saiful
“Access denied for user ‘root’@'localhost’ (using password: YES)” Can anyone tell me how to fix this prob. Pleeeeeeeeeeeeease
and when i execut the 2nd statement i get the output as -I/usr/include/mysql -DBIG_JOINS=1 -fPIC
Also can anyone tell me what is the output file in the 3rd statement.
and when i change the password to NULL i get this
“Access denied for user ‘root’@’localhost’ (using password: NO)”
not able to find out what is the real problem
i also tried using “sudo ./output-file” but it did not work
Those errors are because you haven’t specified the correct password for the mysql server. If you don’t remember the password go here:
http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html
if (mysql_query(conn, “INSERT INTO Meta_Data (alpha, beta, delta, gamma) VALUES (1.01, 2.34, 3.9, 4.3)”)) {
This will put the values into DB OK, but if I try to insert variables, all that gets inserted is 0, for example
if (mysql_query(conn, “INSERT INTO Meta_Data (alpha, beta, delta, gamma) VALUES (alpha, beta, delta, gamma)”)) {
alpha, beta, delta, gamma are declared as doubles & I’ve also tried making them constants but same results. I’m not very strong with C so any advice would be great.
Thanks
John
have a look at the sprintf function to append variables to strings.
gcc: mysql_config -libs: No such file or directory
Thank u
Bhanu
could you able to provide the source code for the drug prescription machine
plz its very imp 2 me for my project
plz help mee
its very urgent
(dlopen(): /usr/lib/imspector/mysqlloggingplugin.so: undefined symbol: compress). Please help me
Below, is the line compilation to program.
g++ mysqlloggingplugin.o libimspector.so -ldl -fPIC -shared -Wl,-soname,mysqlloggingplugin.so -o mysqlloggingplugin.so -L/opt/ef/mysql5/lib/mysql -I/opt/ef/mysql5/include -lmysqlclient -lm -lnsl
char *user = “root”;
char *password = “password”; /* set me first */
char *database = “mysql”;
const char *user = “root”;
const char *password = “password”; /* set me first */
const char *database = “mysql”;
mysql_test.cpp: In function ‘int main()’:
mysql_test.cpp:10: warning: deprecated conversion from string constant to ‘char*’
mysql_test.cpp:11: warning: deprecated conversion from string constant to ‘char*’
mysql_test.cpp:12: warning: deprecated conversion from string constant to ‘char*’
mysql_test.cpp:13: warning: deprecated conversion from string constant to ‘char*’
mysql_test.cpp:21: error: ‘exit’ was not declared in this scope
mysql_test.cpp:27: error: ‘exit’ was not declared in this scope
/tmp/ccwZLvOo.o:(.data.DW.ref.__gxx_personality_v0[DW.ref.__gxx_personality_v0]+0×0): undefined reference to `__gxx_personality_v0′
I have tried the above c code.
But while compiling i get an error message saying:
mysql_c.c: In function ‘main’:
mysql_c.c:5: error: ‘MYSQL’ undeclared (first use in this function)
mysql_c.c:5: error: (Each undeclared identifier is reported only once
mysql_c.c:5: error: for each function it appears in.)
mysql_c.c:5: error: ‘conn’ undeclared (first use in this function)
mysql_c.c:6: error: ‘MYSQL_RES’ undeclared (first use in this function)
mysql_c.c:6: error: ‘res’ undeclared (first use in this function)
mysql_c.c:7: error: ‘MYSQL_ROW’ undeclared (first use in this function)
mysql_c.c:7: error: expected ‘;’ before ‘row’
mysql_c.c:20: warning: incompatible implicit declaration of built-in function ‘exit’
mysql_c.c:26: warning: incompatible implicit declaration of built-in function ‘exit’
mysql_c.c:33: error: ‘row’ undeclared (first use in this function)
I am using Fedora 11.
-Hemant
sudo apt-get install mysql-server mysql-client
mysql -uroot -p
sudo apt-get install libmysqlclient16-dev
gcc -o mysql-c-api-test `mysql_config --cflags` mysql-c-api-test.c `mysql_config --libs`
./mysql-c-api-test
CODE EXPLANATION:
I have declared some variables
//declared variables
unsigned char a,b,c,d;
char buffer[50];
sprintf(buffer,”%02X:%02X:%02X:%02X”,a,b,c,d);
if (mysql_query(conn, “INSERT INTO events (srcAddress) VALUES (‘buffer’)”))
{
fprintf(stderr, “%s\n”, mysql_error(conn));
exit(1);
}
./mysql-c-api-test
Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)
/tmp/ccCldxTF.o: In function `main’:
mysql-c-api.c:(.text+0×31): undefined reference to `mysql_init’
mysql-c-api.c:(.text+0×79): undefined reference to `mysql_real_connect’
mysql-c-api.c:(.text+0×89): undefined reference to `mysql_error’
mysql-c-api.c:(.text+0xc4): undefined reference to `mysql_query’
mysql-c-api.c:(.text+0xd4): undefined reference to `mysql_error’
mysql-c-api.c:(.text+0×107): undefined reference to `mysql_use_result’
mysql-c-api.c:(.text+0×133): undefined reference to `mysql_fetch_row’
mysql-c-api.c:(.text+0x14a): undefined reference to `mysql_free_result’
mysql-c-api.c:(.text+0×156): undefined reference to `mysql_close’
collect2: ld returned 1 exit status
Please help me
Adrián
“Create a C/C++ console application which connects to MySQL database and inserts a new column of type varchar into a given table. Application should ask the user for table and new column name.”
Please let me know what are the modifications/changes that I have to make for the code given here so that I the get desired result.
mysql-devel packages is must
yum install mysql-devel
so mysql.h don’t is in include directory, is in mysql, so you need to add mysql directory in header file.
can u pls help me out to write a program in C++ to connect to MySQL server and also to display the number of hosts connected to it?
warning: incompatible implicit declaration of built-in function ‘exit’
Segmentation fault
Rgds
Ahmad
Program compilation was done successfully with few warnings but when I run it, gave me following error.
Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ (2)
what might be the problem?
Thank you for the article, it was really helpful.
I have done the below steps in Ubuntu and getting the sock error. can anyone please help me as soon as possible.
OS: Gnu/Linux
Version: 2.6.18-194.el5
64Bit.
gcc -o output-file $(mysql_config –cflags) test_mysql.c $(mysql_config –libs)
/usr/bin/ld: skipping incompatible /usr/lib/libmysqlclient.so when searching for -lmysqlclient
/usr/bin/ld: cannot find -lmysqlclient
collect2: ld returned 1 exit status
But when i put it in my makefile.basic , it’s shows me undefined error to mysql.
here is mine, pls correct me. I has been on internet for a week but still can’t manage to solve it.
#CC=powerpc-linux-gcc
CP=/usr/bin/cp
CFLAGS=-g -Wall -L/usr/lib/mysql -lmysqlclient
htdocs=/htdocs
cgi_bin=/cgi-bin
config=/etc/apache2/sites-available/default
” Write a C/C++ program that connects to a MySQL server and checks if the InnoDB plug-in is installed on it. If so, your program should print the total number of disk writes by MySQL.”
please send me
Write a C/C++ program to add a user to MySQL. The user should be permitted to only “INSERT” into the given database..??
jesus.c:25: warning: passing argument 1 of âprintfâ from incompatible pointer type
jesus.c:31: warning: passing argument 1 of âprintfâ from incompatible pointer type
/usr/bin/ld: cannot find -lmysql
collect2: ld returned 1 exit status
Another way to compile: gcc mysql-c-api.c -o output-file $(mysql_config –cflags –libs)
Checkconn.c:16:7: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
Checkconn.c:21:7: warning: incompatible implicit declaration of built-in function ‘exit’ [enabled by default]
/tmp/ccXSAFWL.o: In function `main’:
Checkconn.c:(.text+0×31): undefined reference to `mysql_init’
Checkconn.c:(.text+0×79): undefined reference to `mysql_real_connect’
Checkconn.c:(.text+0×89): undefined reference to `mysql_error’
Checkconn.c:(.text+0xc3): undefined reference to `mysql_query’
Checkconn.c:(.text+0xd3): undefined reference to `mysql_error’
Checkconn.c:(.text+0×105): undefined reference to `mysql_use_result’
Checkconn.c:(.text+0×139): undefined reference to `mysql_fetch_row’
Checkconn.c:(.text+0×150): undefined reference to `mysql_free_result’
Checkconn.c:(.text+0x15c): undefined reference to `mysql_close’
collect2: error: ld returned 1 exit status
root@ubuntu-VirtualBox:~/Desktop/workspace# ./mysql12
Access denied for user ‘root’@'localhost’ (using password: YES)
i am already logged into root???
/etc/bin/init.d/mysqld restart;
mysqladmin -u root password newpasswd
gcc -o output-file $(mysql_config –cflags) mysql-c-api.c $(mysql_config –libs)