C語言訪問MySQL資料庫簡單一實例

來源:互聯網
上載者:User

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庫。

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. #include <mysql.h>  
  4. #include <stdlib.h>  
  5. main()  
  6. {  
  7.         MYSQL *conn;  
  8.         MYSQL_RES *res;  
  9.         MYSQL_ROW row;  
  10.         char *server = "mysql";  
  11.         char *user = "huzia";  
  12.         char *password = "cjrIwo"; /*  */  
  13.         char *database = "huzia";  
  14.         conn = mysql_init(NULL);  
  15.   
  16.         /* Connect to database */  
  17.         if (!mysql_real_connect(conn, server,  
  18.         user, password, database, 0, NULL, 0)) {  
  19.         fprintf(stderr, "%s\n", mysql_error(conn));  
  20.                 exit(1);  
  21.         }  
  22.   
  23.         /* send SQL query */  
  24.         if (mysql_query(conn, "show tables")) {  
  25.                 fprintf(stderr, "%s\n", mysql_error(conn));  
  26.                 exit(1);  
  27.         }  
  28.   
  29.         res = mysql_use_result(conn);  
  30.         /* output table name */  
  31.         printf("MySQL Tables in mysql database:\n");  
  32.         while ((row = mysql_fetch_row(res)) != NULL)  
  33.         printf("%s \n", row[0]);  
  34.   
  35.         /* close connection */  
  36.         mysql_free_result(res);  
  37.         mysql_close(conn);  
  38. }  

運行成功。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.