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 : 我的程序如下:
- #include<mysql.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- static void output_error(MYSQL * mysql);
- int main(int argc, char* argv[]) {
- MYSQL mysql;
- MYSQL_RES * result;
- MYSQL_ROW row;
- MYSQL_FIELD * fields;
- const char* host = "localhost";
- const char* user = "root";
- const char* password = "root";
- const char* database = "test";
- const int port = 3306;
- const char* socket = NULL;
- const int flag = 0;
- const char* sql ;
- int num_fields;
- unsigned long * lengths;
- int i;
- //initialize the database
- if(!mysql_init(&mysql) ) {
- output_error(&mysql);
- }
- printf("mysql initialized successfully ! /n");
- //connect to the database;
- if(!mysql_real_connect(&mysql, host, user, password, database, port, socket, flag)) {
- output_error(&mysql);
- }
- printf("mysql connect successfully! /n");
- printf("/n/n/nthe content of the table data in the database test/n");
- printf("-----------------------------------------------------------/n");
- //do the select query on the database;
- sql = "select * from data" ;
- //printf("%d : %d/n", sizeof(sql), strlen(sql)); // 4:18 sizeof(sql):the size of point --(4); strlen(sql):
- if( mysql_real_query(&mysql, sql, strlen(sql)) ){
- output_error(&mysql);
- }
- //fetch the the result set of the query!
- result = mysql_store_result(&mysql);
- if(result) {
- fields = mysql_fetch_fields(result); // fetch the struct of result
- num_fields = mysql_num_fields(result); // fetch the number of result fields;
- //lengths = mysql_fetch_lengths(result);
- for(i=0; i<num_fields; i++) {
- printf("%s/t", fields[i].name );
- }
- printf("/n");
- while(row = mysql_fetch_row(result)) {
- for(i=0; i<num_fields; i++) {
- printf("%s /t", row[i]);
- }
- printf("/n");
- }
- //release the result of set for release the memory
- mysql_free_result(result);
- }
- else {
- output_error(&mysql);
- }
- printf("/n/n-----------------------------------------------------------/n");
- //close the connetion to the database
- mysql_close(&mysql);
- return 0;
- }
- static void output_error(MYSQL * mysql) {
- fprintf(stderr, "errorno: %d /n", mysql_errno(mysql) );
- fprintf(stderr, "error info: %s/n", mysql_error(mysql) );
- exit(1);
- }
3. 編譯 鏈接,測試:
- wzb@wzb-desktop:~/test$ gcc -o db_test db_test.c -lmysql
- wzb@wzb-desktop:~/test$ ./db_test
- mysql initialized successfully !
- mysql connect successfully!
- the content of the table data in the database test
- -----------------------------------------------------------
- id nodeId data flag time
- 1 0 0 0 2011-03-31 18:19:40
- 2 1 1 2 2011-03-31 18:29:05
- -----------------------------------------------------------
- wzb@wzb-desktop:~/test$
注意鏈接動態庫的選項 : -lmysql
4.對mysql c開發幾個有用的命令:ldd, mysql_config, file ,nm
ldd: 輸出對動態庫的依賴,即依賴的動態庫的信息;
mysql_conf :可以獲得對mysql的配置開發的信息: mysql_config -- libs
看一下,這幾個命令的輸出情況:
- wzb@wzb-desktop:~/test$ ldd db_test
- linux-gate.so.1 => (0x00f40000)
- libmysql.so.16 => /usr/local/lib/libmysql.so.16 (0x0020f000)
- libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0x006bf000)
- libpthread.so.0 => /lib/tls/i686/cmov/libpthread.so.0 (0x004e4000)
- libm.so.6 => /lib/tls/i686/cmov/libm.so.6 (0x00110000)
- /lib/ld-linux.so.2 (0x00af6000)
- wzb@wzb-desktop:~/test$ file db_test
- 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
- wzb@wzb-desktop:~/test$ nm db_test
- 08049de4 d _DYNAMIC
- 08049ec0 d _GLOBAL_OFFSET_TABLE_
- 08048c88 R _IO_stdin_used
- w _Jv_RegisterClasses
- 08049dd4 d __CTOR_END__
- 08049dd0 d __CTOR_LIST__
- 08049ddc d __DTOR_END__
- 08049dd8 d __DTOR_LIST__
- 08048dcc r __FRAME_END__
- 08049de0 d __JCR_END__
- 08049de0 d __JCR_LIST__
- 08049f24 A __bss_start
- 08049f18 D __data_start
- 08048c40 t __do_global_ctors_aux
- 08048830 t __do_global_dtors_aux
- 08049f1c D __dso_handle
- w __gmon_start__
- 08048c3a T __i686.get_pc_thunk.bx
- 08049dd0 d __init_array_end
- 08049dd0 d __init_array_start
- 08048bd0 T __libc_csu_fini
- 08048be0 T __libc_csu_init
- U __libc_start_main@@GLIBC_2.0
- U __stack_chk_fail@@GLIBC_2.4
- 08049f24 A _edata
- 08049f2c A _end
- 08048c68 T _fini
- 08048c84 R _fp_hw
- 08048684 T _init
- 08048800 T _start
- 08049f28 b completed.5790
- 08049f18 W data_start
- U exit@@GLIBC_2.0
- U fprintf@@GLIBC_2.0
- 08048860 t frame_dummy
- 08048884 T main
- U mysql_close
- U mysql_errno
- U mysql_error
- U mysql_fetch_fields
- U mysql_fetch_row
- U mysql_free_result
- U mysql_init
- U mysql_num_fields
- U mysql_real_connect
- U mysql_real_query
- U mysql_store_result
- 08048b66 t output_error
- 08049f20 d p.5788
- U printf@@GLIBC_2.0
- U putchar@@GLIBC_2.0
- U puts@@GLIBC_2.0
- 08049f24 B stderr@@GLIBC_2.0
- wzb@wzb-desktop:~/test$
- wzb@wzb-desktop:~/test$ mysql_config
- Copyright 2009 Sun Microsystems, Inc.
- This software comes with ABSOLUTELY NO WARRANTY. This is free software,
- and you are welcome to modify and redistribute it under the GPL license
- Get compiler flags for using the MySQL client library.
- Usage: mysql_config [OPTIONS]
- --cflags [-I/usr/local/include]
- -?, --help Display this help and exit.
- --include [-I/usr/local/include]
- --libs [-L/usr/local/lib -lmysql -lpthread]
- --libs_r [-L/usr/local/lib -lmysql -lpthread]
- --version [6.0.2]
- wzb@wzb-desktop:~/test$ mysql_config --libs
- -L/usr/local/lib -lmysql -lpthread
- wzb@wzb-desktop:~/test$ mysql_config --libs_r
- -L/usr/local/lib -lmysql -lpthread
- wzb@wzb-desktop:~/test$ mysql_config --include
- -I/usr/local/include
- wzb@wzb-desktop:~/test$
下文的鏈接:http://www.cyberciti.biz/tips/linux-unix-connect-mysql-c-api-program.html
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):
- * Simple C program that connects to MySQL Database server*/
- #include <mysql.h>
- #include <stdio.h>
- main() {
- MYSQL *conn;
- MYSQL_RES *res;
- MYSQL_ROW row;
- char *server = "localhost";
- char *user = "root";
- char *password = "PASSWORD"; /* set me first */
- char *database = "mysql";
- 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);
- }
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