C語言訪問MySQL資料庫簡單一實例
不像Oracle, MYSQL資料庫並不支援嵌入式SQL語言。
但是提供了功能強大的C,C++支援API,其中c語言的API在參考手冊的第25部分,獨立於這個3000多頁的參考手冊之外的另外部分的
MySQL++是用於C++的MySQL API。Warren Young負責該項目。要想瞭解更多資訊,請訪問http://www.mysql.com/products/mysql++/。
當然mysql似乎最為廣泛的應用是個php指令碼語言一起,apache,一起用做網站的後台資料庫服務程式,這個做過好多。
同時我是一個C程式員,碰到什麼總是想用c試試,這幾天忙著準備軍轉考試,
剛好有點閑暇時間,順便把c和mysql資料庫的訪問再複習一遍。
運行環境是SunOS x4100 5.10 Generic_118855-33 i86pc i386 i86pc;編譯器是gcc,外加Llibmysqlclient庫。
- #include <stdio.h>
- #include <string.h>
- #include <mysql.h>
- #include <stdlib.h>
- main()
- {
- MYSQL *conn;
- MYSQL_RES *res;
- MYSQL_ROW row;
- char *server = "mysql";
- char *user = "huzia";
- char *password = "cjrIwo"; /* */
- char *database = "huzia";
- conn = mysql_init(NULL);
-
- /* Connect to database */
- if (!mysql_real_connect(conn, server,
- user, password, database, 0, NULL, 0)) {
- fprintf(stderr, "%s\n", mysql_error(conn));
- exit(1);
- }
-
- /* send SQL query */
- if (mysql_query(conn, "show tables")) {
- fprintf(stderr, "%s\n", mysql_error(conn));
- exit(1);
- }
-
- res = mysql_use_result(conn);
- /* output table name */
- printf("MySQL Tables in mysql database:\n");
- while ((row = mysql_fetch_row(res)) != NULL)
- printf("%s \n", row[0]);
-
- /* close connection */
- mysql_free_result(res);
- mysql_close(conn);
- }
運行成功。