標籤:
codeblocks 編寫C檔案串連mysql資料庫
codeblocks 設定。
1.設定lib庫檔案:
Settings->Compiler settings->Linker settings->link libraries: add添加 C:\Program Files\MySQL\MySQL Server 5.5\lib\libmysql.lib
2.設定.h標頭檔:
Settings->Compiler settings->Search directories->Compiler: add 添加 C:\Program Files\Microsoft SDKs\Windows\v6.0A\include
以上兩步都只需引入即可。
[3.注意libmysql.dll檔案,若檔案丟失可下載,下載後放在 C:\Windows\System32下即可]
C ->mySQL 查詢資料
1 #include <stdio.h> 2 #include <winsock2.h> 3 #include <mysql.h> 4 /*資料庫連接用宏*/ 5 #define HOST "localhost"//本地 6 #define USERNAME "root"//dbms user name 7 #define PASSWORD "123456"//password 8 #define DATABASE "mydb"//database name 9 void query_sql(char* sql);10 int main()11 {12 char *query;13 query="select * from students";//查詢學生表14 query_sql(query);15 return 0;16 }17 void query_sql(char* sql)18 {19 MYSQL my_connection; /*這是一個資料庫連接*/20 int res; /*執行sql語句後的返回標誌*/21 MYSQL_RES *res_ptr; /*指向查詢結果的指標*/22 MYSQL_FIELD *field; /*欄位結構指標*/23 MYSQL_ROW result_row; /*按行返回的查詢資訊*/24 int row, column; /*查詢返回的行數和列數*/25 int i, j;26 /*初始化mysql串連my_connection*/27 mysql_init(&my_connection);28 /*建立mysql串連*/29 if (NULL != mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD,30 DATABASE, 0, NULL, CLIENT_FOUND_ROWS)) /*串連成功*/31 {32 printf("資料庫查詢query_sql串連成功!\n");33 /*設定查詢編碼為gbk,以支援中文*/34 mysql_query(&my_connection, "set names gbk");35 res = mysql_query(&my_connection, sql);36 if (res) /*執行失敗*/37 {38 printf("Error: mysql_query !\n");39 /*關閉串連*/40 mysql_close(&my_connection);41 }42 else /*現在就代表執行成功了*/43 {44 /*將查詢的結果給res_ptr*/45 res_ptr = mysql_store_result(&my_connection);46 /*如果結果不為空白,就把結果print*/47 if (res_ptr)48 {49 /*取得結果的行數和*/50 column = mysql_num_fields(res_ptr);51 row = mysql_num_rows(res_ptr);52 printf("查詢到 %d 行 \n", row);53 /*輸出結果的欄位名*/54 for (i = 0; field = mysql_fetch_field(res_ptr); i++)55 printf("%10s ", field->name);56 printf("\n");57 /*按行輸出結果*/58 for (i = 1; i < row+1; i++)59 {60 result_row = mysql_fetch_row(res_ptr);61 for (j = 0; j < column; j++)62 printf("%10s ", result_row[j]);63 printf("\n");64 }65 }66 /*不要忘了關閉串連*/67 mysql_close(&my_connection);68 }69 }70 else71 {72 printf("資料庫連接失敗");73 }74 }
【codeblocks配置】C對Mysql資料的查詢