linux c mysql 实例

作者:fly 发布于:2015-1-2 13:05 分类:Linux

www.forwhat.cn

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

MYSQL *mysql_main;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;
void display_header();
void display_row();
int main(int argc,char *argv[])
{
    int res;
    int first_row = 1;

    mysql_main = mysql_init(NULL);

    if(!mysql_main)
    {
        fprintf(stderr,"mysql_init failed\n");
        return EXIT_FAILURE;
    }
    mysql_main = mysql_real_connect(mysql_main,"localhost","test","test","test",0,NULL,0);
    if(mysql_main)
    {
        printf("Connection success:\n");
        res = mysql_query(mysql_main,"SELECT childno,fname,age FROM children WHERE age>5");
        if(res)
        {
            fprintf(stderr,"SELECT error: %s\n",mysql_error(mysql_main));
        }
        else
        {
            res_ptr = mysql_use_result(mysql_main);
            if(res_ptr)
            {
                while((sqlrow = mysql_fetch_row(res_ptr)))
                {
                    if(first_row)
                    {
                        display_header();
                        first_row = 0;
                    }
                    display_row();
                }
            }
        }
    }
    else
    {
        printf("Connection failed\n");
    }
    mysql_close(mysql_main);
    return EXIT_SUCCESS;
}
void display_header()
{
    MYSQL_FIELD *field_ptr;
    printf("Column details:\n");
    while((field_ptr = mysql_fetch_field(res_ptr))!=NULL)
    {
        printf("\t Name: %s\n",field_ptr->name);
        printf("\t Type: ");
        if(IS_NUM(field_ptr->type))
        {
            printf("Numeric filed\n");
        }
        else
        {
            switch(field_ptr->type)
            {
            case FIELD_TYPE_VAR_STRING:
                printf("VARCHAR\n");
                break;
            case FIELD_TYPE_LONG:
                printf("LONG\n");
                break;
            default:
                printf("Type is %d,check in mysql_com.h\n",field_ptr->type);
            }
        }
        printf("\t MAX width %ld\n",field_ptr->length);
        if(field_ptr->flags&AUTO_INCREMENT_FLAG)
            printf("\t Auto increments\n");
        printf("\n");
    }
}
void display_row()
{
    unsigned int field_count;

    field_count = 0;
    while(field_count<mysql_field_count(mysql_main))
    {
        if(sqlrow[field_count]) printf("%s ",sqlrow[field_count]);
        else printf("NULL");
        field_count++;
    }
    printf("\n");
}

 

 

发表评论:

 
Powered by emlog sitemap