No announcement yet.

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


Unconfigured Ad Widget

  • Filter
  • Time
  • Show
Clear All
new posts

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

    WordPress Hosting on SSD Servers
    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. One 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 summarizes 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 itselfgcc, make and other development libs: GNU C compiler

    Sample C Program

    Following are the instructions that 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.
    /* 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 */

  • #2
    ASP.Net Hosting starts @ $3.18/Mo.
    Re: How do I write a C program to connect MySQL database server?

    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!



    Sign up for a News Letter Click here to sign up