用C api 連接mysql數據庫的 開發實例

1. 下載mysql c connector 安裝包; 有兩種方法:

                 1 下載tar文件, 將其中的的 lib, include , bin 都放在 /usr/local 相應的目錄下;

2. 也可配置鏈接庫的附加目錄 : sudo vi /etc/ld.so.conf 文件中加入你的連接器的lib目錄;

                 3. 好像也可以用 sudo apt-get install libmysqclient-dev

                                        對於c++的好像是 sudo apt-get install libmysql++-dev

2.編輯 C 程序利用mysql c api : 我的程序如下:

  1. #include<mysql.h> 
  2. #include<stdio.h> 
  3. #include<stdlib.h> 
  4. #include<string.h> 
  5. static void output_error(MYSQL * mysql); 
  6. int main(int argc, char* argv[]) { 
  7.      MYSQL mysql; 
  8.      MYSQL_RES * result; 
  9.      MYSQL_ROW row; 
  10.      MYSQL_FIELD * fields; 
  11.     const char* host = "localhost"
  12.     const char* user = "root"
  13.     const char* password = "root"
  14.     const char* database = "test"
  15.     const int   port = 3306; 
  16.     const char* socket = NULL; 
  17.     const int flag = 0; 
  18.     const char* sql ;    
  19.     int num_fields; 
  20.     unsigned long * lengths; 
  21.     int i; 
  22.     //initialize the database  
  23.     if(!mysql_init(&mysql) ) { 
  24.         output_error(&mysql); 
  25.     } 
  26.     printf("mysql initialized successfully ! /n"); 
  27.     //connect to the database; 
  28.     if(!mysql_real_connect(&mysql, host, user, password, database, port, socket, flag)) { 
  29.         output_error(&mysql); 
  30.     } 
  31.     printf("mysql connect successfully! /n"); 
  32.     printf("/n/n/nthe content of the table data in the database test/n"); 
  33.     printf("-----------------------------------------------------------/n"); 
  34.     //do the select query on the database; 
  35.     sql = "select * from data"
  36.     //printf("%d : %d/n", sizeof(sql), strlen(sql)); // 4:18 sizeof(sql):the size of point --(4); strlen(sql): 
  37.     if( mysql_real_query(&mysql, sql, strlen(sql)) ){ 
  38.         output_error(&mysql); 
  39.     } 
  40.     //fetch the the result set of the query!         
  41.     result = mysql_store_result(&mysql); 
  42.     if(result) { 
  43.         fields = mysql_fetch_fields(result);    // fetch the struct of result         
  44.         num_fields = mysql_num_fields(result);  // fetch the number of result fields; 
  45.          
  46.         //lengths = mysql_fetch_lengths(result);     
  47.         for(i=0; i<num_fields; i++) { 
  48.             printf("%s/t", fields[i].name ); 
  49.         } 
  50.         printf("/n"); 
  51.         while(row = mysql_fetch_row(result)) { 
  52.             for(i=0; i<num_fields; i++) { 
  53.                 printf("%s /t",  row[i]); 
  54.              } 
  55.              printf("/n"); 
  56.         } 
  57.         //release the result of set  for release the memory 
  58.         mysql_free_result(result);   
  59.          
  60.     } 
  61.     else
  62.         output_error(&mysql); 
  63.     } 
  64.     printf("/n/n-----------------------------------------------------------/n"); 
  65.     //close the connetion to the database 
  66.     mysql_close(&mysql); 
  67.     return 0; 
  68. static void output_error(MYSQL * mysql) { 
  69.     fprintf(stderr, "errorno: %d /n", mysql_errno(mysql) ); 
  70.     fprintf(stderr, "error info: %s/n", mysql_error(mysql) ); 
  71.     exit(1); 

3. 編譯 鏈接,測試:

  1. wzb@wzb-desktop:~/test$ gcc -o db_test db_test.c -lmysql  
  2. wzb@wzb-desktop:~/test$ ./db_test 
  3. mysql initialized successfully !  
  4. mysql connect successfully!  
  5. the content of the table data in the database test 
  6. ----------------------------------------------------------- 
  7. id  nodeId  data    flag    time     
  8. 1   0   0   0   2011-03-31 18:19:40      
  9. 2   1   1   2   2011-03-31 18:29:05      
  10. ----------------------------------------------------------- 
  11. wzb@wzb-desktop:~/test$  

注意鏈接動態庫的選項 : -lmysql

4.對mysql c開發幾個有用的命令:ldd, mysql_config, file ,nm

ldd: 輸出對動態庫的依賴,即依賴的動態庫的信息;

mysql_conf  :可以獲得對mysql的配置開發的信息: mysql_config -- libs

看一下,這幾個命令的輸出情況:

  1. wzb@wzb-desktop:~/test$ ldd db_test 
  2.     linux-gate.so.1 =>  (0x00f40000) 
  3.     libmysql.so.16 => /usr/local/lib/libmysql.so.16 (0x0020f000) 
  4.     libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0x006bf000) 
  5.     libpthread.so.0 => /lib/tls/i686/cmov/libpthread.so.0 (0x004e4000) 
  6.     libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0x00110000) 
  7.     /lib/ld-linux.so.2 (0x00af6000) 
  8. wzb@wzb-desktop:~/test$ file db_test 
  9. db_test: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, not stripped 
  10. wzb@wzb-desktop:~/test$ nm db_test 
  11. 08049de4 d _DYNAMIC 
  12. 08049ec0 d _GLOBAL_OFFSET_TABLE_ 
  13. 08048c88 R _IO_stdin_used 
  14.          w _Jv_RegisterClasses 
  15. 08049dd4 d __CTOR_END__ 
  16. 08049dd0 d __CTOR_LIST__ 
  17. 08049ddc d __DTOR_END__ 
  18. 08049dd8 d __DTOR_LIST__ 
  19. 08048dcc r __FRAME_END__ 
  20. 08049de0 d __JCR_END__ 
  21. 08049de0 d __JCR_LIST__ 
  22. 08049f24 A __bss_start 
  23. 08049f18 D __data_start 
  24. 08048c40 t __do_global_ctors_aux 
  25. 08048830 t __do_global_dtors_aux 
  26. 08049f1c D __dso_handle 
  27.          w __gmon_start__ 
  28. 08048c3a T __i686.get_pc_thunk.bx 
  29. 08049dd0 d __init_array_end 
  30. 08049dd0 d __init_array_start 
  31. 08048bd0 T __libc_csu_fini 
  32. 08048be0 T __libc_csu_init 
  33.          U __libc_start_main@@GLIBC_2.0 
  34.          U __stack_chk_fail@@GLIBC_2.4 
  35. 08049f24 A _edata 
  36. 08049f2c A _end 
  37. 08048c68 T _fini 
  38. 08048c84 R _fp_hw 
  39. 08048684 T _init 
  40. 08048800 T _start 
  41. 08049f28 b completed.5790 
  42. 08049f18 W data_start 
  43.          U exit@@GLIBC_2.0 
  44.          U fprintf@@GLIBC_2.0 
  45. 08048860 t frame_dummy 
  46. 08048884 T main 
  47.          U mysql_close 
  48.          U mysql_errno 
  49.          U mysql_error 
  50.          U mysql_fetch_fields 
  51.          U mysql_fetch_row 
  52.          U mysql_free_result 
  53.          U mysql_init 
  54.          U mysql_num_fields 
  55.          U mysql_real_connect 
  56.          U mysql_real_query 
  57.          U mysql_store_result 
  58. 08048b66 t output_error 
  59. 08049f20 d p.5788 
  60.          U printf@@GLIBC_2.0 
  61.          U putchar@@GLIBC_2.0 
  62.          U puts@@GLIBC_2.0 
  63. 08049f24 B stderr@@GLIBC_2.0 
  64. wzb@wzb-desktop:~/test$  

  1. wzb@wzb-desktop:~/test$ mysql_config 
  2. Copyright 2009 Sun Microsystems, Inc. 
  3. This software comes with ABSOLUTELY NO WARRANTY. This is free software, 
  4. and you are welcome to modify and redistribute it under the GPL license 
  5. Get compiler flags for using the MySQL client library. 
  6. Usage: mysql_config [OPTIONS] 
  7.   --cflags            [-I/usr/local/include] 
  8.   -?, --help          Display this help and exit. 
  9.   --include           [-I/usr/local/include] 
  10.   --libs              [-L/usr/local/lib -lmysql -lpthread] 
  11.   --libs_r            [-L/usr/local/lib -lmysql -lpthread] 
  12.   --version           [6.0.2] 
  13. wzb@wzb-desktop:~/test$ mysql_config --libs 
  14. -L/usr/local/lib -lmysql -lpthread 
  15. wzb@wzb-desktop:~/test$ mysql_config --libs_r 
  16. -L/usr/local/lib -lmysql -lpthread 
  17. wzb@wzb-desktop:~/test$ mysql_config --include 
  18. -I/usr/local/include 
  19. wzb@wzb-desktop:~/test$  


下文的鏈接:http://www.cyberciti.biz/tips/linux-unix-connect-mysql-c-api-program.html

Howto: Connect MySQL server using C program API under Linux or UNIX

by Vivek Gite on May 31, 2007 · 56 comments

From my mailbag:

How do I write a C program to connect MySQL database server?

MySQL database does support C program API just like PHP or perl.

The C API code is distributed with MySQL. It is included in the mysqlclient library and allows C programs to access a database.

Many of the clients in the MySQL source distribution are written in C. If you are looking for examples that demonstrate how to use the C API, take a look at these clients. You can find these in the clients directory in the MySQL source distribution.

Requirements

Make sure you have development environment installed such as gcc, mysql development package etc. Following is the list summarize the list of packages to compile program:

  • mysql: MySQL client programs and shared library
  • mysqlclient: Backlevel MySQL shared libraries (old libs)
  • mysql-devel: Files for development of MySQL applications (a must have)
  • mysql-server: Mysql server itself
  • gcc, make and other development libs: GNU C compiler

Sample C Program

Following instructions should work on any Linux distro or UNIX computer. Here is the small program that connects to mysql server and list tables from mysql database.(download link):

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







How do I compile and link program against MySQL libs?

MySQL comes with a special script called mysql_config. It provides you with useful information for compiling your MySQL client and connecting it to MySQL database server. You need to use following two options.
Pass --libs option - Libraries and options required to link with the MySQL client library.

$ mysql_config --libs
Output:

-L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto

Pass --cflags option - Compiler flags to find include files and critical compiler flags and defines used when compiling the libmysqlclient library.
$ mysql_config --cflags
Output:

-I/usr/include/mysql -g -pipe -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing

You need to pass above option to GNU C compiler i.e. gcc. So to compile above program, enter:
$ gcc -o output-file $(mysql_config --cflags)mysql-c-api.c $(mysql_config --libs)
Now execute program:
$ ./output-file
Output:

MySQL Tables in mysql database:


columns_priv


db


func


help_category


help_keyword


help_relation


help_topic


host


tables_priv


time_zone


time_zone_leap_second


time_zone_name


time_zone_transition


time_zone_transition_type


user 

References:

  • MySQL C API - A must read - official MySQL C API documentation
發佈了28 篇原創文章 · 獲贊 2 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章