標籤:
初學C,看到C 串連mysql的教程不是很多,遇到很多的問題,看過許多盟友的解決方案,有點模糊(對我這個菜鳥來說),下面貼出具體步驟,一起學習:
1.C串連mysql的方法:C ,C ++ ,ODBC ,java ,Net .......,這裡看C的串連,首先進入mysql驅動官網下載connector/c http://dev.mysql.com/downloads/connector/ 選擇C版下載
2.C 在vc 6環境下串連mysql :下面貼出源碼(看別人寫的,以此作參考)
#include "stdafx.h"#include <stdio.h>#include <winsock2.h>#include <mysql.h>#include <stdlib.h>/*資料庫連接用宏*/#define HOST "localhost"#define USERNAME "root"#define PASSWORD "root"#define DATABASE "test"void query_sql(char* sql);int main(){ char *query; query="select * from a"; query_sql(query);system("pause"); return 0;}void query_sql(char* sql){ MYSQL my_connection; /*這是一個資料庫連接*/ int res; /*執行sql語句後的返回標誌*/ MYSQL_RES *res_ptr; /*指向查詢結果的指標*/ MYSQL_FIELD *field; /*欄位結構指標*/ MYSQL_ROW result_row; /*按行返回的查詢資訊*/ int row, column; /*查詢返回的行數和列數*/ int i, j; /*初始化mysql串連my_connection*/ mysql_init(&my_connection); /*建立mysql串連*/ if (NULL != mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, CLIENT_FOUND_ROWS)) /*串連成功*/ { printf("資料庫查詢query_sql串連成功!\n"); /*設定查詢編碼為gbk,以支援中文*/ mysql_query(&my_connection, "set names gbk"); res = mysql_query(&my_connection, sql); if (res) /*執行失敗*/ { printf("Error: mysql_query !\n"); /*關閉串連*/ mysql_close(&my_connection); } else /*現在就代表執行成功了*/ { /*將查詢的結果給res_ptr*/ res_ptr = mysql_store_result(&my_connection); /*如果結果不為空白,就把結果print*/ if (res_ptr) { /*取得結果的行數和*/ column = mysql_num_fields(res_ptr); row = mysql_num_rows(res_ptr); printf("查詢到 %d 行 \n", row); /*輸出結果的欄位名*/ for (i = 0; field = mysql_fetch_field(res_ptr); i++) printf("%10s ", field->name); printf("\n"); /*按行輸出結果*/ for (i = 1; i < row+1; i++) { result_row = mysql_fetch_row(res_ptr); for (j = 0; j < column; j++) printf("%10s ", result_row[j]); printf("\n"); } } /*不要忘了關閉串連*/ mysql_close(&my_connection); } } else { printf("資料庫連接失敗"); }}
3.加入標頭檔所需要的mysql.h所需要的庫
步驟:工具==》》選項==》》目錄(點擊此選項)==》》include files 選擇添加
3.加入mysql.h的實現,在win平台為libmysql.lib檔案(至於為什麼是lib檔案,看圖理解或者自己上網理解)
3.在環境編譯時間加入此檔案libmsql.lib步驟:
工程==》設定==》串連 (選此選項卡)==》在對象/庫模組中加入libmysql.lib
4.此時再講動態串連庫libmysql.dll複製到要發布的realse/debug 目錄下(因為dll 是動態運行時才載入的可執行檔,此時確保能正常運行)一定要這步,不然會報錯說找不到這個檔案
5.編譯運行:結果
總結:
C串連資料庫有兩種形式。一種是官方提供的C驅動包,另一種是ODBC的串連。代碼中引入的檔案mysql.h 是對mysql的操作的聲明,實現的方法檔案是libmysqld.DLL 檔案,而libmysql.lib 檔案是為了編譯時間能加入libmysqld.dll的函數讓編譯器通過,知道有此函數的實現。但是這種串連方法是和mysql資料庫耦合在一起的,代碼的可維護性非常不好,推薦使用ODBC吧(愚解)。
C 串連mysql VC的步驟