用c語言正確讀取MySQL數(shù)據(jù)庫實戰(zhàn)演示
以下的文章主要向大家描述的是用c語言正確讀取MySQL數(shù)據(jù)庫的實際操作流程,如果你對用c語言正確讀取MySQL數(shù)據(jù)庫的正確操作流程感興趣的話,那么以下的文章就會滿足你的好奇之心了。
最近一段時間我們學(xué)習(xí)了linux操作系統(tǒng)下的C開發(fā),呵呵,寫了一個測試程序,作用是讀取MySQL的數(shù)據(jù),然后顯示出來。經(jīng)測試成功…
- #include <stdio.h>
- #include <stdlib.h>
- #include <MySQL.h>
- #define DB_SERVER ""
- #define DB_NAME "test"
- #define DB_USER "root"
- #define DB_PWD ""
- static MySQL *db_handel,MySQL;
- static MySQL_ROW row;
- static int query_error;
- MySQL_RES *query_test(char *sql);
- int query_show(MySQL_RES *result);
- int main(int argc,char *argv[])
- {
- MySQL_RES * results;
- results=query_test("select * from test");
獲取記錄
- query_show(results);
顯示記錄
- return 0;
- }
查詢記錄
- MySQL_RES *query_test(char *sql)
- {
- static MySQL_RES *query_result;
- printf("%s\n",sql);
- MySQL_init(&MySQL);
- db_handel=MySQL_real_connect(&MySQL,DB_SERVER,DB_USER,DB_PWD,DB_NAME,0,0,0);
打開讀取MySQL數(shù)據(jù)庫連接
- if(db_handel==NULL)
錯誤處理
{
- printf(MySQL_error(&MySQL));
- return NULL;
- }
- query_error=MySQL_query(db_handel,sql);
查詢
- if(query_error!=0)
錯誤處理
- {
- printf(MySQL_error(db_handel));
- return NULL;
- }
- query_result=MySQL_store_result(db_handel);
獲取記錄
- MySQL_close(db_handel);
關(guān)閉數(shù)據(jù)庫
- return query_result;
返回記錄
- }
顯示記錄
- int query_show(MySQL_RES *result)
- {
- unsigned int i,num_fields;
- MySQL_FIELD *fileds;
- num_fields=MySQL_num_fields(result);
獲取字段數(shù)
- fileds=mysql _fetch_fields(result);
獲取字段數(shù)組
- while((row=mysql_fetch_row(result))!=NULL)
循環(huán)顯示
- {
- for(i=0;i<num_fields;i++)
- {
- printf("%s: %s \n",fileds[i].name,row[i]?row[i]:"NULL");
- }
- }
- return 0;
- }
以下是MakeFile文件內(nèi)容
- CC=gcc
- #LDLIBS=`gtk-config --libs --cflags`
- LDLIBS=-L /usr/lib/mysql -I /usr/include/mysql -l mysqlclient
- CFLAGS=-Wall -g`gtk-config --cflags`
- window:window.c
- $(CC) $(LDLIBS) window.c -o window
- #window.o:window.c
- # $(CC) $(LDLIBS) -c window.c
- clean:
- rm -f window
- rm -f *.o
以上的相關(guān)內(nèi)容就是對c語言讀取Mysql的介紹,望你能有所收獲。
【編輯推薦】
- MySQL 資源的正確應(yīng)用
- MySQL數(shù)據(jù)庫的基本操作演示
- MySQL 免安裝版的實際配置方法
- 重置MySQL數(shù)據(jù)庫密碼的實際操作流程
- MySQL簡單命令概述