linux下c操作mysql之增刪改查
阿新 • • 發佈:2019-02-17
/************************************************************ FileName : demo.c FileFunc : C語言介面訪問MySQL Version : V0.1 Author : JeffSui Date : 2014-02-20 Descp : c查詢mysql資料庫遍歷輸出 *************************************************************/ #include <stdio.h> #include <stdlib.h> #include "/usr/include/mysql/mysql.h" int main(int argc,char *argv[]) { MYSQL my_connection,*conn_ptr; MYSQL_RES *res_ptr; MYSQL_ROW sqlrow; int iRet; int iTableRow,iTableCol,i,j; char *server = "localhost"; char *user = "root"; char *password = ""; char *database = "csql"; unsigned int uiTimeOut = 7;//設定連線超時7s conn_ptr = mysql_init(&my_connection);//初始化連線控制代碼 if( !conn_ptr ) { fprintf(stderr,"mysql_init failed ! \n"); return EXIT_FAILURE; } iRet = mysql_options(&my_connection,MYSQL_OPT_CONNECT_TIMEOUT,(const char *)&uiTimeOut);//設定連線超時 if( iRet ) { fprintf(stderr,"Connection is timeout! \n"); return EXIT_FAILURE; } conn_ptr = mysql_real_connect(&my_connection,server,user,password,database,0,NULL,0);//連線資料庫 if( conn_ptr ) { printf("Connection success!\n"); iRet = mysql_query(&my_connection,"select * from children");//執行SQL語句 if( iRet ) { fprintf(stderr,"select error %d: %s !\n",mysql_errno(&my_connection),mysql_error(&my_connection));//>列印錯誤處理具體資訊 return EXIT_FAILURE; } res_ptr = mysql_store_result(&my_connection);//集合 if( res_ptr ) { iTableRow = mysql_num_rows(res_ptr);//行 iTableCol = mysql_num_fields(res_ptr);//列 for(i=0; i<iTableRow; i++) { sqlrow = mysql_fetch_row(res_ptr); for(j=0; j<iTableCol; j++) { printf("%-8s ",sqlrow[j]);//字串向左靠,右補空格 } printf("\n"); } mysql_free_result(res_ptr);//完成對資料的所有操作後,呼叫此函式來讓MySQL庫清理它分配的物件 } 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; }