c 连接 mysql

#include <stdio.h> 
#include <stdlib.h> 
#include "mysql.h" 
/*
* mysql_sample.c 
* 
* MySQL client program sample code 
* 
* by Robert on 2006.02.09 
* Anta Systems, Inc. 
* 
* Compile options: 
*   gcc -I/usr/include/mysql -L/usr/lib/mysql -o mysql_sample mysql_sample.c -lmysqlclient -lz 
* 
*/

/* global definition */ 
#define CONN_HOST "192.168.100.112" 
#define CONN_USER "test" 
#define CONN_PASS "" 
#define CONN_DB   "test" 

/* global MySQL handler */
 
MYSQL mysql; 
void exiterr(int exitcode) 
{ 
    fprintf( stderr, "%s\n", mysql_error(&mysql) ); 
    exit(exitcode); 
} 

int mysql_test()
 
{ 
    MYSQL_RES *res; 
    MYSQL_ROW row; 
    uint i = 0; 
      /* 1. init MySQL handler */ 
   if (!mysql_init(&mysql)) 
    { 
        exiterr(-1); 
    }

      /* 2. connect to MySQL */ 
   if (!mysql_real_connect(&mysql, CONN_HOST , CONN_USER , CONN_PASS, NULL , MYSQL_PORT, NULL, 0)) 
    { 
        exiterr(-2); 
    } 

    
/* 3. select Database */
 
    if (mysql_select_db(&mysql, CONN_DB)) 
    { 
        exiterr(-3); 
    }

      /* 4. excute a query */ 
   char *sqlstr = "SELECT * FROM test_table"; 
    if (mysql_query(&mysql, sqlstr)) 
    { 
        exiterr(-4); 
    }

      /* 5. store result */ 
   if (!(res = mysql_store_result(&mysql))) 
    { 
        exiterr(-5); 
    }

    /* 6. fetch row and get the result */ 
    while((row = mysql_fetch_row(res))) 
    { 
        for (i=0 ; i < mysql_num_fields(res); i++) 
        { 
            printf("%s, ",row[i]); 
        } 
        printf("\n"); 
    }

      /* 7. free result */ 
   mysql_free_result(res);

      /* 8. close MySQL Connection */ 
   mysql_close(&mysql); 
}

int main() 
{ 
    mysql_test(); 
    return 0; 

}

你可能感兴趣的:(c 连接 mysql)