faqts : Computers : Databases : MySQL : Connectivity : C

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

59 of 86 people (69%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Where can I get an example C program using MySQL?

Jan 27th, 2000 08:32
Nathan Wallace, Allen Zhao


Here is an example C program taken from the mySQL book.

char sql_command[2048];

int mysql_update_string_field(char *db_name, char *table_name, 
                              char *field_name, char *field_value, 
                              char *whereclause)
{
    MYSQL_RES       *result;
    MYSQL *connection, mysql;
    int state;

    sprintf(sql_command, "update %s set %s=\"%s\" where %s", 
            table_name, field_name, field_value, whereclause);
    // connect to the mySQL database at localhost
    mysql_init(&mysql);
    connection = mysql_real_connect(&mysql, 
                                    sql_host, /*IP, server name, or
                                              localhost, or just NULL 
                                              for localhost*/
                                    sql_user, /*user name*/
                                    sql_auth, /*password*/
                                    db_name,  /*db name*/
                                    0,        /*port number*/
                                    NULL,     /*Unix socket name: 
                                              an addition of 3.23?*/
                                    0);       /*client_flag*/
    // check for a connection error
    if (connection ==NULL) return 0;

    state = mysql_query(connection,  sql_command); 
    if (state!=0) return 0;
    // must call mysql_store_result() before we can issue any other
    // query calls
    result = mysql_store_result(connection);
    // free the result set
    mysql_free_result(result);
    // close the connection
    mysql_close(connection);
    return 1;
}