#include <stdio.h> #include <stdlib.h> #include <syslog.h> #include "mysql.h" int main(int argc, char * argv[]) { MYSQL my_connection; MYSQL_RES * my_res; MYSQL_ROW row; MYSQL_FIELD * fields; char str[30]; int res; int i; mysql_init(&my_connection); if (mysql_real_connect(&my_connection, "192.168.1.30", "root", "mysql", "sun", 0, NULL, 0)) { printf("connect succeed!\n"); /* res = mysql_query(&my_connection, "insert into buddy(user_id, friend_id, nickname, signature)\ values(1001, 112233, 'kaka', 'god')"); */ res = mysql_query(&my_connection, "select user.user_name, buddy.friend_id, buddy.nickname, buddy.signature\ from buddy join user on buddy.user_id = user.user_id where user_name = 'Robert' order by friend_id"); if (!res){ my_res = mysql_store_result(&my_connection); //print colunm int num_fields = mysql_num_fields(my_res); fields = mysql_fetch_fields(my_res); for (i = 0; i < num_fields; i++) { printf("%s ", fields[i].name); } printf("\n"); //print results while ( (row = mysql_fetch_row(my_res)) != NULL) { int * lengths = mysql_fetch_lengths(my_res); for (i = 0; i < num_fields; i++){ printf("%s ", row[i] ? row[i] : "NULL"); } memset(str, 0, sizeof(str)); memcpy(str, row[2], strlen(row[2])); printf("[in c variable: %s]", str); printf("\n"); } mysql_free_result(my_res); } else{ printf("search error\n"); } mysql_close(&my_connection); } else { printf("fail to connect to mysql, error:%s\n", mysql_error(&my_connection)); } return EXIT_SUCCESS; }