码迷,mamicode.com
首页 > 数据库 > 详细

C 语言访问MySQL数据库的简单实验

时间:2014-12-27 17:37:53      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:mysql   数据库   linux   

首先,建立一个MySQL用户rick,密码设置为6452079,登录地点设置为本地登录localhost。

为rick用户创建一个数据库foo。

在数据库foo里创建一个表children。

表的结构如下:

技术分享

添加3条简单的记录后,表为:

技术分享

实验C 代码:

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

MYSQL my_connection;
MYSQL_RES *res_ptr;
MYSQL_ROW sqlrow;

void mysql_display_row( MYSQL *my_connect, MYSQL_ROW sqlrow )
{
    unsigned int field_count;
    unsigned int field_result = mysql_field_count( my_connect );
    field_count = 0;
    
    while( field_count < field_result ) {
        printf("%s ", sqlrow[field_count]);
        field_count++;
    }
    printf("\n");
}

int main()
{
    int res;
    mysql_init( &my_connection );
    if( NULL != mysql_real_connect( &my_connection, "localhost", "rick", "6452079", "foo", 0, NULL, 0 ) ) {
        printf("Connection success!\n");
        res = mysql_query( &my_connection, "SELECT childno, fname, age FROM children WHERE age>5" );
        if ( 0 != res )
            printf("SELECT error: %s\n", mysql_error( &my_connection ));
        else {
            res_ptr = mysql_use_result( &my_connection );
            if( NULL != res_ptr ) {
                //  printf("Retrieved %lu rows\n", (unsigned long)mysql_num_rows( res_ptr ));
                while( (sqlrow = mysql_fetch_row( res_ptr ) ) ) {
                       printf("Fetched data...\n");
                       mysql_display_row( &my_connection, sqlrow );
                }
                if( 0 != mysql_errno( &my_connection) )
                       fprintf(stderr, "Retrieve error: %s\n", mysql_error( &my_connection ) );
                mysql_free_result( res_ptr );
            }

            mysql_close( &my_connection );
        }
    }
    else {
            fprintf(stderr, "Connection failed\n");
            if( mysql_errno( &my_connection ) )
                fprintf(stderr, "Connection error %d: %s\n", mysql_errno( &my_connection ), mysql_error( &my_connection ) );
        }

    return EXIT_SUCCESS;
}

运行结果:

技术分享


C 语言访问MySQL数据库的简单实验

标签:mysql   数据库   linux   

原文地址:http://blog.csdn.net/u014488381/article/details/42193685

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!