這幾天忙著寫一支C語言的程式將門禁系統的原始資料轉檔然後轉存到MySQL資料庫中,之前就聽說了MySQL有提供C API可用,但是要搞清楚如何取得Dev C++,然後用這個API可說是最具有挑戰性的,這裡有一些簡單的步驟可以幫你設定然後執行,這些步驟假定你已經安裝了Dev C++ 、mysql並且也在執行中,還有可以寫出C語言程式的知識,在我的系統中有安裝xampp使用apache伺服器來提供web介面到mysql,假如你有這樣做你可以建立自己的資料庫,連結資料庫然後執行查詢,但是今天這個教學只會使用預先安裝的mysql 資料庫。
[adsense][/adsense]
步驟 1
下載安裝Dev C++的mysql devpak
步驟 2
開啟Dev C++ 然後到工具→編譯器選項(如下圖)
在編譯器選項的對話視窗新增下列的命令到連結器輸入方塊中:-lmysql,如下圖
就是這樣了,現在確定你的mysql有在執行,然後準備好設計程式!
步驟 3
複製下面的程式碼到Dev C++,假如幸運的話應該可以編譯成功。
#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>
#include <windows.h>
#include <mysql/mysql.h>
static char *opt_host_name = "localhost"; /* server host (default=localhost) */
static char *opt_user_name = "root"; /* username (default=login name) */
static char *opt_password = ""; /* password (default=none) */
static unsigned int opt_port_num = 3306; /* port number (use built-in value) */
static char *opt_socket_name = NULL; /* socket name (use built-in value) */
static char *opt_db_name = "mysql"; /* database name (default=none) */
static unsigned int opt_flags = 0; /* connection flags (none) */
int main (int argc, char *argv[])
{
MYSQL *conn; /* pointer to connection handler */
MYSQL_RES *res; /* holds the result set */
MYSQL_ROW row;
/* initialize connection handler */
conn = mysql_init (NULL);
/* connect to server */
mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
opt_db_name, opt_port_num, opt_socket_name, opt_flags);
/* show tables in the database (test for errors also) */
if(mysql_query(conn, "show tables"))
{
fprintf(stderr, "%s n", mysql_error(conn));
printf("Press any key to continue. . . ");
getch();
exit(1);
}
res = mysql_use_result(conn); /* grab the result */
printf("Tables in databasen");
while((row = mysql_fetch_row(res)) != NULL)
printf("%s n", row[0]);
/* disconnect from server */
mysql_close (conn);
printf("Press any key to continue . . . ");
getch();
return 0;
} /* end main function */
如果幸運的話可以看到下面的輸出
看到沒,已經可以成功連結到mysql伺服器了!可以看看 Dev-Cppdocslibmysql 這個資料夾裡有一個mysql手冊包含了完整的文件,這裡頭有提供C api提供的函式,假如你要找一個簡易教學來使用api可以檢視下面的連結,裡面有程式碼跟許多的範例,有趣吧。
注意: Vista的使用者,在嘗試執行.exe的時候你會看到vista抱怨沒有發現libmysql.dll,假如有這等情事發生複製在Dev-Cppbin裡的這個檔案到.exe檔案所載的資料夾中。
http://www.kitebird.com/mysql-book/ch06-2ed.pdf
有問題或建議就請直接留言給我