Linux連線mysql資料庫(C語言)
阿新 • • 發佈:2020-11-13
###作業系統Ubuntu14.04###
###mysql5.5.7###
###連線資料庫,進行操作###
#include <stdio.h> #include <stdlib.h> #include <mysql/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","root","123","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"); }
編譯程式報錯:
gcc -o mysql mysql.c
檢視相關文件發現是未引入相關的庫檔案導致連結錯誤。詳情參考mysql官方網站,連結如下:
https://dev.mysql.com/doc/c-api/5.6/en/c-api-building-clients.html
重新輸入編譯命令:
gcc mysql.c -lmysqlclient -o mysql
編譯連結完美通過!
執行程式 ./mysql