以下的範例是使用C語言來達成MySQL的連結,本文是參考http://codex.wiki/post/106065-844
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "/usr/include/mysql/mysql.h" int main(){ MYSQL mysql,*sock; MYSQL_RES *res; MYSQL_ROW row; char qbuf[160] = "select afield,bfield,cfield,dfield from tablename where tran = 1 limit 0,1"; mysql_init(&mysql); if (!(sock = mysql_real_connect(&mysql,"localhost","dbuser","dbpassword","dbname",0,NULL,0))){ fprintf(stderr,"Couldnt connect to engine!n%snn",mysql_error(&mysql)); perror(""); exit(1); } if(mysql_query(sock,qbuf)) { fprintf(stderr,"Query failed (%s)n",mysql_error(sock)); exit(1); } if (!(res=mysql_store_result(sock))) { fprintf(stderr,"Couldnt get result from %sn", mysql_error(sock)); exit(1); } printf("number of fields returned: %dn",mysql_num_fields(res)); while((row = mysql_fetch_row(res))) { printf("afield:%s ,bfield:%s, cfield:%s, dfield:%s",row[0],row[1],row[2],row[3]) ; puts( "\nquery ok !n" ) ; } mysql_free_result(res); mysql_close(sock); exit(0); return 0; }
編繹時我是使用下面命令
gcc -Wall mysql.c -o mysql `mysql_config --cflags --libs`
文章標籤
全站熱搜
留言列表