C 語言訪問MySQL資料庫的簡單實驗

來源:互聯網
上載者:User

標籤: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資料庫的簡單實驗

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.