This is more about C than it is about MySQL.  But hopefully a few
pointers will get you going.  Look at the source for the different
client programs (e.g., client/mysqlshow.c) for lots of uses of the
C API.

Note that mysql_init does NOT allocate any memory for you.  You have
to pass it a pointer to EXISTING memory.  The conventional way to do
this is shown below.  The mysql_use_result() function DOES allocate
memory for you.  That's why you need to call mysql_free_result later
on, so that you don't hog memory that you don't need any more.

If you don't understand specific parts of the sample programs, then
ask about them and we'll do our best to answer them!  Below is a simple
program.

Tim

Here's a very simple program:

#include <mysql/mysql.h>
#include <stdlib.h>
#include <stdio.h>

int
main()
{
    MYSQL mysql;
    MYSQL_RES *result;
    char buf[64];

    mysql_init(&mysql);         /* set up the MYSQL object */
    if (!mysql_real_connect(&mysql, 0, "USER", "PASSWORD",
                            "DATABASE", 0, 0, 0))       /* connect */
    {
        fprintf(stderr, "can't connect to database: %s\n",
                mysql_error(&mysql));
        exit(EXIT_FAILURE);
    }

    sprintf(buf, "select version(), database()");
    /* NOTE: mysql_query returns 0 on success.  So, you need to test
     * for NOT mysql_query (or mysql_query(...) == 0) to see if it
     * worked */
    if (!mysql_query(&mysql, buf) && (result = mysql_use_result(&mysql))) {
        MYSQL_ROW answer = mysql_fetch_row(result);
        printf("Version: %s, Database %s\n", answer[0], answer[1]);
        (void) mysql_fetch_row(result); /* read eof() */

        mysql_free_result(result);      /* release memory to OS */
    }
    else {
        fprintf(stderr, "can't perform query: %s\n",
                mysql_error(&mysql));
        exit(EXIT_FAILURE);
    }

    mysql_close(&mysql);

    return EXIT_SUCCESS;
}

-----------------------------------------------------------
Send a mail to [EMAIL PROTECTED] with
unsubscribe mysql [EMAIL PROTECTED]
in the body of the message to unsubscribe from this list.

Reply via email to