Linux下C连接MySQL数据库方法


Linux下C连接MySQL数据库方法:
  1. #include<stdlib.h>  
  2. #include<stdio.h>  
  3.   
  4. #include<mysql.h>  
  5.   
  6. int main(int argc,char* argv[])  
  7. {  
  8.     MYSQL *conn_ptr;  
  9.   
  10.     conn_ptr = mysql_init(NULL);  
  11.     if(!conn_ptr){  
  12.         fprintf(stderr,"mysql_init failed\n");  
  13.         return EXIT_FAILURE;  
  14.     }     
  15.   
  16.     conn_ptr = mysql_real_connect( conn_ptr, "localhost", "li", "li","mysql", 0, NULL, 0 );  
  17.   
  18.     if(conn_ptr){  
  19.         printf("Connection success\n");  
  20.     }else{  
  21.         printf( "Connection failed\n");  
  22.     }     
  23.   
  24.     mysql_close( conn_ptr );  
  25.   
  26.     return 0;  
  27. }  

编译方法:

gcc $(mysql_config --cflags) xxx.c -o xxx $(mysql_config --libs)

方法二:gcc test.c -o test -L/user/lib/mysql -lmysqlclient                成功!

方法三:gcc test.c -o test $(mysql_config --cflags) $(mysql_config --libs)

或者:gcc test.c -o test $(mysql_config --cflags --libs)                        成功!

相关内容