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