LINUX下C语言连接mysql实例源码介绍



LINUX下C语言连接mysql实例源码介绍,

插入操作:

[cpp] view plaincopy

  1. #include   
  2. #include   
  3. int main(int argc,char *argv[])  
  4.  
  5.  MYSQL conn;  
  6.  int res;     
  7.  mysql_init(&conn);//初始化 连接  
  8.  if(mysql_real_connect(&conn,”localhost”,”root”,”123″,”test”,0,NULL,CLIENT_FOUND_ROWS))  
  9.   
  10.     printf(“数据库连接成功/n”);  
  11.     res mysql_query(&conn,”insert into test values(‘user’,’123456′)”);//插入语句,成功返回0,失败返回1  
  12.     if(res)  
  13.      
  14.         printf(“语句执行失败/n”);  
  15.         mysql_close(&conn);//记得关闭连接  
  16.      
  17.     else  
  18.      
  19.         printf(“语句执行成功/n”);  
  20.         mysql_close(&conn);  
  21.      
  22.          
  23.  return 0;  
  24.  

查询操作:

[cpp] view plaincopy


  1. void query_sql(char* sql)   
  2.  
  3.     MYSQL my_connection;   
  4.     int res;   
  5.     MYSQL_RES *res_ptr;   
  6.     MYSQL_FIELD *field;   
  7.     MYSQL_ROW result_row;   
  8.   
  9.     int row, column;   
  10.     int i, j;   
  11.   
  12.       
  13.     mysql_init(&my_connection);  
  14.   
  15.       
  16.     if (mysql_real_connect(&my_connection, HOST, USERNAME, PASSWORD,  
  17.                DATABASE, 0, NULL, CLIENT_FOUND_ROWS))   
  18.      
  19.           
  20.         printf(“数据库查询query_sql连接成功!n”);  
  21.           
  22.         mysql_query(&my_connection, “set names utf8″);  
  23.           
  24.           
  25.         res mysql_query(&my_connection, sql);  
  26.   
  27.         if (res)   
  28.           
  29.             printf(“Error: mysql_query !n”);  
  30.               
  31.             mysql_close(&my_connection);  
  32.          
  33.         else   
  34.           
  35.               
  36.               
  37.             res_ptr mysql_store_result(&my_connection);  
  38.   
  39.               
  40.             if (res_ptr)   
  41.              
  42.                   
  43.                 column mysql_num_fields(res_ptr);  
  44.                 row mysql_num_rows(res_ptr) 1;  
  45.                 printf(“查询到 %lu 行 n”, row);  
  46.   
  47.                   
  48.                 for (i 0; field mysql_fetch_field(res_ptr); i++)  
  49.                     printf(“%st”, field->name);  
  50.                 printf(“n”);  
  51.   
  52.                   
  53.                 for (i 1; row; i++)  
  54.                  
  55.                     result_row mysql_fetch_row(res_ptr);  
  56.                     for (j 0; column; j++)  
  57.                         printf(“%st”, result_row[j]);  
  58.                     printf(“n”);  
  59.                  
  60.   
  61.              
  62.   
  63.               
  64.             mysql_close(&my_connection);  
  65.          
  66.      
  67.  

 

编译:gcc -o test_mysql test_mysql.c `mysql_config –cflags –libs`

插入 删除 更新操作返回一个整形数值,以判断成功与否。查询返回的更复杂。