From my mailbag:

How do I write a C program to connect MySQL database server?

MySQL database does support C program API just like PHP or perl.

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.


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 <mysql.h>
#include <stdio.h>

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));

   /* send SQL query */
   if (mysql_query(conn, "show tables")) {
      fprintf(stderr, "%s\n", mysql_error(conn));

   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 */

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.

$ mysql_config --libs

-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.
$ mysql_config --cflags

-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:
$ gcc -o output-file $(mysql_config --cflags) mysql-c-api.c $(mysql_config --libs)
Now execute program:
$ ./output-file

MySQL Tables in mysql database:


  • MySQL C API – A must read – official MySQL C API documentation

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 94 comments so far... add one
CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
94 comments… add one
  • Jonathan Arnold Jun 1, 2007 @ 15:08

    One thing to be aware of though with the mysql library – there is licensing involved. It was complicated enough that our company backed off from MySQL and went with SQLite.

    • secret Mar 27, 2011 @ 21:19

      Thank you for the code, but I have a question
      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 ^.^

  • 🐧 nixCraft Jun 1, 2007 @ 21:09


    You have raised an excellent point.

    MySQL dual Licensing policy is bit dangerous; if you are giving out GPL code it can be done with GPL; otherwise it force commercial vendor under its own terms and condition.

    PGSQL or SQLite seems to good alternative.

    Appreciate your post!

    • dinesh Jun 23, 2010 @ 6:40

      i am not being able to install Microsoft SQL Server JDBC Driver 2.0 in my laptop..can u give my some tips for that???

  • david Jun 4, 2007 @ 14:11

    I’m no C guru, but I think there’s a typo. shouldn’t you run:


    or compile with:

    -o output.file

    Or, am I missing something?

  • 🐧 nixCraft Jun 4, 2007 @ 14:55


    Thanks for the heads up!

  • debakanta sandha Jul 12, 2007 @ 13:19

    i want to connect mysql from c program in linux mandriva 2007.i am not being able to do it as mysql.h is not there in mandriva 2007

  • 🐧 nixCraft Jul 12, 2007 @ 14:25

    Just install mysql-devel package

  • John Matthews Aug 6, 2007 @ 13:34

    How do you specify the socket file?

  • 🐧 nixCraft Aug 6, 2007 @ 15:04

    Use mysql_real_connect() and set host to NULL socket to NULL or 0

    mysql_real_connect(&mysql, 0, username, password, dbname, 0, 0, 0 ); 

    See API doc for more help!

  • Edwind Oct 19, 2007 @ 0:38

    how i do a makefile that compile me the .c?

    it has to find the result of mysql_config –libs and –cflags and put it in the gcc -o line

    thx in advance

  • Walther Nov 12, 2007 @ 16:17

    Hi Edwind,

    I’m not big on c-fu, but you should “vi Makefile” in the directory where you have your .c program and in the Makefile, you should type something along the lines of:

    MYSQLCFLAGS=`mysql_config –cflags`
    MYSQLLIBS=`mysql_config –libs`
    $(CC) -I/usr/include/mysql -o datafoxclient $(MYSQLCFLAGS) datafoxclient.c $(MYSQLLIBS)
    rm -f datafoxclient

    some of the c-fu gurus would probably tell you that my Makefile is broken and not that good! But, hey, it works for me 🙂

    hope that helps 🙂

  • anil Nov 30, 2007 @ 4:40

    i want c code for FTP server and client.

  • bedjo Dec 6, 2007 @ 17:42

    any scaffolding for C available ? so i don’t have to
    code add/edit/delete bla bla bla etc ?


  • siva Feb 8, 2008 @ 18:23

    ./output-file output not created while compile mysql-c-api.c in gcc as specified in procedure
    plz anyone help me

  • semarsuper Feb 23, 2008 @ 13:52

    Combining your script there with memcached C API ( will also boost the performance, instead of directly querying to mysqld.



  • Saiful Islam Mar 28, 2008 @ 5:54

    i m facing a error message when wanna run output file-
    “error while loading shared libraries: cannot open shared object file: No such file or directory”

    would anyone help me to over come this prob.


  • Skatox Apr 6, 2008 @ 19:56

    Excelent Bro! thanks for the info. It helped me a lot.

  • shiva Apr 11, 2008 @ 10:40

    i hav followed same procedure which is given above for executing n i m getting an error message when wanna run output file-
    “Access denied for user ‘root’@’localhost’ (using password: YES)” Can anyone tell me how to fix this prob. Pleeeeeeeeeeeeease

  • tomato Apr 13, 2008 @ 16:03

    shiva, if you have problems of this level, you shouldn’t be programming.

  • champ May 4, 2008 @ 13:11

    I encountered with problems about it, but when I see your site and apply what you said, I could finally succeed it.

    Thanks a lot..

  • zackaria Sep 5, 2008 @ 7:59

    a have 2 table or more, how to make connect n operation in c.

  • kishore Oct 15, 2008 @ 5:19

    hi,thanks for the code which you gave but i am getting some errors.i tried running the code on ubuntu8.04,when i execute the 1st statement –“$ mysql_config –libs” i get the output as -Wl,-Bsymbolic-functions -L/usr/lib/mysql -lmysqlclient
    and when i execut the 2nd statement i get the output as -I/usr/include/mysql -DBIG_JOINS=1 -fPIC

    i am not able to get the output as mentioned in the post.Can anyone please help me??
    Also can anyone tell me what is the output file in the 3rd statement.

    thankyou 🙂

  • sher Dec 14, 2008 @ 3:15

    “Access denied for user ‘root’@’localhost’ (using password: YES)”
    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

  • Johan Hedberg Jan 19, 2009 @ 7:51

    Those errors are because you haven’t specified the correct password for the mysql server. If you don’t remember the password go here:

  • Edg Mar 3, 2009 @ 3:18

    Thank you for a great tutorial, I did it with the server of my website, but I had to give permission to my IP to access the server.

  • Vineesh poduval May 1, 2009 @ 4:28

    i am using TC …from where i will get the the mysql.h file for turbo c(windows)

    • 🐧 nixCraft May 1, 2009 @ 4:53

      I don’t think so TC supports mysql API. Get better compiler set or move to GNU/Linux.

  • John_L May 8, 2009 @ 7:40

    Hey great tutorial, but I’m having problems inserting double values & when I try to retrieve the values using the C application, all I see is the primary key column. Here is my insert code:
    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.

    Would anyone have any advice to get around this?

  • cca May 15, 2009 @ 2:48

    john_l the c compiler will see your variables as strings, not as variables.
    have a look at the sprintf function to append variables to strings.

    man sprintf

  • John Brock May 19, 2009 @ 19:42

    If you see an error regarding ‘exit’ implicit function, remember to add an include of stdlib.h or process.h. Otherwise, good starting program for MySQL programming.

  • Bhanu Jun 11, 2009 @ 5:13

    Hi walter ,

    I Wrote makefile as u suggested for one of the member ,i have problem while doing make,it cannot find

    gcc: mysql_config -cflags: No such file or directory
    gcc: mysql_config -libs: No such file or directory

    where i should find it ,

    PLZ help me out
    Thank u

    • raja Feb 21, 2012 @ 4:23

      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

  • Henrique Leitão Jun 30, 2009 @ 19:59

    Hi, I have mysql4 and mysql5 running in my linux. I set the path lib and the path include in compilation to paths mysql5. The program compile, but occurs a erro when program is execute.
    (dlopen(): /usr/lib/imspector/ undefined symbol: compress). Please help me
    Below, is the line compilation to program.
    g++ mysqlloggingplugin.o -ldl -fPIC -shared -Wl,-soname, -o -L/opt/ef/mysql5/lib/mysql -I/opt/ef/mysql5/include -lmysqlclient -lm -lnsl

  • grufo Aug 4, 2009 @ 13:44

    to compile the litte script with gcc = 4.3 i had to inlcude “#include ” and had to change those four lines from:

    char *server = “localhost”;
    char *user = “root”;
    char *password = “password”; /* set me first */
    char *database = “mysql”;


    const char *server = “localhost”;
    const char *user = “root”;
    const char *password = “password”; /* set me first */
    const char *database = “mysql”;

    and the compile command needed this additional flag: “-lstdc++”

    gcc -lstdc++ -o mysql_test $(mysql_config –cflags) mysql_test.cpp $(mysql_config –libs)

    otherwise i got the following errors:
    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]+0x0): undefined reference to `__gxx_personality_v0′

  • Hemant Sep 22, 2009 @ 8:03

    I have tried the above c code.
    But while compiling i get an error message saying:

    mysql_c.c:1:19: error: mysql.h: No such file or directory
    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)

    Which certainly means that i dont have mysql.h file.
    I am using Fedora 11.

    Can anyone solve this problem for me. Please.

    Thanks in Advance.

  • aardvark Oct 11, 2009 @ 12:15

    This works in ubuntu 9.04

    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`

  • SK Oct 18, 2009 @ 9:34

    Hey I have problem similar to John_L. I want to push variable declared in C into the database.
    I have declared some variables
    //declared variables
    unsigned char a,b,c,d;

    and want to push these variables in MYSQL database using MYSQL C API. I used sprintf and pushed all variables in a string variable.

    //declared the string.
    char buffer[50];

    //used sprintf function to format variables into string.

    now pushed “buffer” into database using mysql c api

    // Insert into MySQL
    if (mysql_query(conn, “INSERT INTO events (srcAddress) VALUES (‘buffer’)”))
    fprintf(stderr, “%sn”, mysql_error(conn));

    But instead of writing values of the variable buffer, “buffer” is as it is getting written in the database.

    Can anyone plz help me to get through this problem.

  • Korting Oct 19, 2009 @ 12:37

    Thanks for the code and the updates here above 🙂

  • sunny Oct 21, 2009 @ 3:46

    Please help me fix this problem. I try to run the above exmple but I get the error like this
    Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2)

  • Gandhi Nov 24, 2009 @ 20:21

    I’m getting this.
    /tmp/ccCldxTF.o: In function `main’:
    mysql-c-api.c:(.text+0x31): undefined reference to `mysql_init’
    mysql-c-api.c:(.text+0x79): undefined reference to `mysql_real_connect’
    mysql-c-api.c:(.text+0x89): 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+0x107): undefined reference to `mysql_use_result’
    mysql-c-api.c:(.text+0x133): undefined reference to `mysql_fetch_row’
    mysql-c-api.c:(.text+0x14a): undefined reference to `mysql_free_result’
    mysql-c-api.c:(.text+0x156): undefined reference to `mysql_close’
    collect2: ld returned 1 exit status
    Please help me

    • Adrian Sep 2, 2010 @ 16:23

      Hello Ghandi!

      I have the same exact problem you wrote about. I am running Ubuntu 9.10 and Mysql 5.1.

      Did you ever solve it? Regards,

  • gandhi Nov 24, 2009 @ 20:24

    My question is
    “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.

  • Alok Jan 5, 2010 @ 19:25

    For Centos and other rpm based packages
    mysql-devel packages is must
    yum install mysql-devel

  • Garrett Griffin Jan 11, 2010 @ 18:48

    Huge thanks for this. Exactly what I needed. Other than difficulty finding the MySQL-Devel package for SUSE 11, it was a breeze to get started with C and MySQL.

  • Jose Tapia Feb 26, 2010 @ 5:34

    Thanks a lot for the explanation, was very useful for my Asterisk programming test. Best regards

  • gaurav May 23, 2010 @ 2:48

    great i love this

  • randy melder May 24, 2010 @ 17:24

    perfect tutorial. thanks a million!

  • ahkbar Jun 23, 2010 @ 1:02

    very usefull tuto, for f13 i can’t compile with #include , when i search in my system with command locate: “locate mysql.h” this show /usr/include/mysql/mysql.h
    so mysql.h don’t is in include directory, is in mysql, so you need to add mysql directory in header file.

    thanks this work.

  • maxi Aug 4, 2010 @ 18:17

    I need the code for the following task any one can help me, I need a solution fast

    Write a C/C++ console application that connects to a MySQL server (with InnoDB plugin enabled) and prints information about the last detected deadlock (if any) by the InnoDB Storage Engine.

  • deepak Aug 10, 2010 @ 10:33

    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?

  • DILIP Sep 28, 2010 @ 3:01

    A C/C++ program that connects to a MySQL server and checks intrusion attempts every 5 minutes. If an intrusion attempt is detected beep the internal speaker to alert the administrator. A high number of aborted connects to MySQL at a point in time may be used as a basis of an intrusion.

  • dinesh kumar A.s Nov 12, 2010 @ 17:37

    Write a C/C++ program that connects to a MySQL server and lists all hosts connected to it at that point in time.. can any one find solution coding for this program please.

  • Muksin Dec 13, 2010 @ 1:54

    when i compiling, i get this message
    warning: incompatible implicit declaration of built-in function ‘exit’

    after running
    Segmentation fault

    please help me.

  • Ahmad Hussain Dec 19, 2010 @ 18:20

    Dear I am new in linux Mandriva , my main object is to covert my and Microsoft sql server base project to Linux plate form , I was battling to find out the clue to connect using c with Mysql and your code work for me lot to get clue. Thx lot you are star.

  • supraja Mar 14, 2011 @ 9:57

    Thanks for ginving this code, it is working fine.

  • Karan Mar 28, 2011 @ 11:15

    Thanks, it indeed was of help.

  • Niroshan Apr 4, 2011 @ 11:42

    I have Lampp installed. When I run mysql_config –libs I was asked to install ‘libmysqlclient15-dev’. When I run mysql_config command with libs and cflags after installing libmysqlclient15-dev it didn’t give me the exact output as you have specified but -L/usr/lib/mysql -lmysqlclient and -I/usr/include/mysql was there respectively.
    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?

    • Niroshan Apr 4, 2011 @ 13:24

      ok creating a symlink to /opt/lampp/mysql/mysql.sock from /var/run/mysqld/mysqld.sock solved the problem.
      Thank you for the article, it was really helpful.

    • prashanth Aug 29, 2012 @ 18:38

      I have done the below steps in Ubuntu and getting the sock error. can anyone please help me as soon as possible.

      rashu@prashu-HP-Pavilion-dv4-Notebook-PC:~/myC/mySQL_prgms$ mysql_config --libs
      The program 'mysql_config' is currently not installed.  You can install it by typing:
      sudo apt-get install libmysqlclient-dev
      prashu@prashu-HP-Pavilion-dv4-Notebook-PC:~/myC/mySQL_prgms$ sudo apt-get install libmysqlclient-dev
      Reading package lists... Done
      rashu@prashu-HP-Pavilion-dv4-Notebook-PC:~/myC/mySQL_prgms$ mysql_config --libs
      -Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql -lmysqlclient
      prashu@prashu-HP-Pavilion-dv4-Notebook-PC:~/myC/mySQL_prgms$ mysql_config --cflags
      -I/usr/include/mysql  -DBIG_JOINS=1  -fno-strict-aliasing   -DUNIV_LINUX -DUNIV_LINUX
      prashu@prashu-HP-Pavilion-dv4-Notebook-PC:~/myC/mySQL_prgms$ gcc -o mySQL_output $(mysql_config --cflags) ./mysql-c-api.c $(mysql_config --libs)
      ./mysql-c-api.c: In function ‘main’:
      ./mysql-c-api.c:17:7: warning: incompatible implicit declaration of built-in function ‘exit’
      ./mysql-c-api.c:22:7: warning: incompatible implicit declaration of built-in function ‘exit’
      prashu@prashu-HP-Pavilion-dv4-Notebook-PC:~/myC/mySQL_prgms$ ./mySQL_output
      Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

      Thanks alot in advance !

  • vijaybhaskar Apr 23, 2011 @ 13:00

    when i run above program in my test machine. i am getting below errors. Could you please tel me how to rectify this.
    OS: Gnu/Linux
    Version: 2.6.18-194.el5

  • vijaybhaskar Apr 23, 2011 @ 13:03

    sorry i forgot to add error message:
    gcc -o output-file $(mysql_config –cflags) test_mysql.c $(mysql_config –libs)
    /usr/bin/ld: skipping incompatible /usr/lib/ when searching for -lmysqlclient
    /usr/bin/ld: cannot find -lmysqlclient
    collect2: ld returned 1 exit status

  • Kevin May 30, 2011 @ 7:30

    Hi it works well for me.
    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.

    CFLAGS=-g -Wall -L/usr/lib/mysql -lmysqlclient



  • Etay Jul 21, 2011 @ 5:37

    Might be good to add another include file #include to handle the exit(1) func properly without warnings from the compiler.

    There is alway a security risk to hard code values from within your code. If you run from the shell $ strings output-file you would be able to see the user credentials along with other data. If you reverse engineer an executable, that would be pretty much step-1. A good exercise to modify the code to enter data from stdin. gets(something) or fgets(something sizeof(something), stdin)… string.h

  • Etay Jul 21, 2011 @ 19:41

    From my previous post, the include file is stdlib.h…

  • Hrehan Jul 30, 2011 @ 10:40

    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.

    Can anyone help me with this program,i have tried it but its showing lots of error msgs..

  • Anusha Rao Jul 31, 2011 @ 15:19

    Hello frd plz give me this program code
    ” 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.”

  • prathap Aug 1, 2011 @ 16:12

    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. i need this question answer as soon as possible please any one tel me….

  • prathap Aug 2, 2011 @ 9:19

    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 answer this question please

  • sunkanna Aug 17, 2011 @ 18:41

    i want source code for dis question
    please send me

    question is
    Write a C/C++ program to add a user to MySQL. The user should be permitted to only “INSERT” into the given database..??

  • cripton Aug 19, 2011 @ 7:24

    #include in order to compile with newer compilers

    • cripton Aug 19, 2011 @ 7:26

      #include “stdlib.h”

  • cripton Aug 19, 2011 @ 7:29

    sorry for the spam.. I wanted to post:

    #include “stdlib.h” in order to compile with newer compilers

  • Adolfo Hernandez Oct 16, 2011 @ 22:50


    I’m compiling as follows:

    gcc -o jesus $(/usr/local/src/inser_m_c/mysql/bin/mysql_config –cflags) jesus.c $(/usr/local/src/inser_m_c/mysql/bin/mysql_config –libs)

    It has an error

    jesus.c: In function âmainâ:
    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

    Thanks for your help


    • Rick Oct 20, 2011 @ 15:56

      I’ve compiled fine under QNX with

      cc -o test $(mysql_config –cflags) test.c $(mysql_config –libs)

      be sure your dev libraries are installed, Jesus your code shows some weird characters ->> âprintfâ

      Best Regards

  • shalini Nov 3, 2011 @ 4:52

    which is the best development tools used to connect mysql server.

  • rehman Nov 13, 2011 @ 10:08

    please explain allthese code and mysqlmethods

  • sabari Nov 17, 2011 @ 6:36

    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 answer this question please…pls send the coding to my mail pls…… its very urgent…

  • Ricky Feb 21, 2012 @ 6:27

    Thanks for your help

  • Freddy Mar 23, 2012 @ 18:13

    Thank you for this!! This was a really great quick tutorial on contacting mysql through a c file. Great beginning to a start in writting c on the server.

  • Leandro Aug 21, 2012 @ 1:11

    This is very cool. Very similar to PHP. Thanks for sharing.
    Another way to compile: gcc mysql-c-api.c -o output-file $(mysql_config –cflags –libs)

  • sanjog Oct 16, 2012 @ 11:58

    I get the following error when I run the above code!!!!

    gcc Checkconn.cCheckconn.c: In function ‘main’:
    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+0x31): undefined reference to `mysql_init’
    Checkconn.c:(.text+0x79): undefined reference to `mysql_real_connect’
    Checkconn.c:(.text+0x89): 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+0x105): undefined reference to `mysql_use_result’
    Checkconn.c:(.text+0x139): undefined reference to `mysql_fetch_row’
    Checkconn.c:(.text+0x150): undefined reference to `mysql_free_result’
    Checkconn.c:(.text+0x15c): undefined reference to `mysql_close’
    collect2: error: ld returned 1 exit status

  • nauman Nov 6, 2012 @ 7:59

    its says the following when i try to run it
    root@ubuntu-VirtualBox:~/Desktop/workspace# ./mysql12
    Access denied for user ‘root’@’localhost’ (using password: YES)
    i am already logged into root???

    • varun Nov 14, 2012 @ 2:46

      first before compiling restart mysqld by using the following coomand:
      /etc/bin/init.d/mysqld restart;

      then set ur password by using:
      mysqladmin -u root password newpasswd

      then in the program in the mysql_connect section give the password section give new password . then compile using the following coomand:
      gcc -o output-file $(mysql_config –cflags) mysql-c-api.c $(mysql_config –libs)

      it will work….

  • Sudhakar Jan 2, 2013 @ 15:00

    Anybody have a code simplecode user value to mysql using C-language please Submit on website

  • Ismael Mar 12, 2014 @ 20:34

    Thank you, it worked at once.

  • Rohan Kadam Aug 30, 2014 @ 18:22

    Hello Sir
    I need to create c api for my php application to add,update,delete and retrieve data from database.I have xampp sever install for php and gcc for c on my windows 7. Please can u give me guidance how can i do this and any tutorial link.

    Thanks in advance and please give me guidance for this.

  • sowmya Oct 9, 2014 @ 11:12

    Works perfect!

  • Jr Apr 6, 2015 @ 0:32

    After 3 weeks trying to compile a c++ / mysql program this post saved life :- )

    The command below worked perfectly!!!!!

    $ gcc -o output-file $(mysql_config –cflags) mysql-c-api.c $(mysql_config –libs)

  • mysql freak Nov 17, 2015 @ 21:59

    Every where i look on the web everybody gives and example of how to use the C API to connect to MySQL but nobody bothered to write an article about how to use the C API to connect to MySQL securely using SSL.

  • Micheal Nov 19, 2015 @ 11:47

    Hi, Thanks for the tutorial.
    My problem is when i try to compile the code I get the error:
    gcc: error: mysql-c-api.c: No such file or directory.

    Does it mean that mysql-c-api.c is the name of the program we just wrote or its something else?

  • Micheal Nov 20, 2015 @ 13:24

    The code works like a charm Thanks

    Can you help with another problem that to add a login page, where users must enter their username and password and only 3 trials. When the credentials are correct then they can access a page with resources.


  • iyed Mar 3, 2016 @ 9:07

    Hello thks fr the amazing code
    Can you help me with somthing , i need to to access to a database using a wampserver can that be done ??

  • Sachin Apr 5, 2016 @ 19:58

    Thanks alot 🙂

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum