- //by: sincoder
- #include <sys/types.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <dirent.h>
- #include <stdlib.h>
- #include <string.h>
- #include <mysql/mysql.h>
- int main(int argc ,char **argv)
- {
- MYSQL conn;
- MYSQL_RES *pRes = NULL;
- MYSQL_FIELD *pField;
- MYSQL_ROW myRow;
- unsigned long *length;
- int num_fields;
- int i;
- MYSQL_FIELD_OFFSET f_offset;
- int res;
- mysql_init(&conn);
- if(!mysql_real_connect(&conn,"localhost","root","heihei","mysql",3360,0,0))
- {
- fprintf(stderr,"connect to mysql server failed\\n");
- return -1;
- }
- printf("Connect OK!\\n");
- mysql_select_db(&conn,"mysql");
- res = mysql_query(&conn,"select * from user");
- if(res != 0)
- {
- fprintf(stderr,"query failed.\\n");
- printf("%d:%s\\n",mysql_errno(&conn),mysql_error(&conn));
- goto out;
- }
- printf("field count:%d\\n",mysql_field_count(&conn));
- //得到 MYSQL_RES .....
- pRes = mysql_store_result(&conn);
- num_fields = mysql_num_fields(pRes);
- pField = mysql_fetch_fields(pRes);
- for(i = 0; i < num_fields; i++)
- {
- printf("Field %u is %s type:%d\\n", i, pField[i].name,pField[i].type);//254 -> string
- }
- while((myRow = mysql_fetch_row(pRes)))
- {
- length = mysql_fetch_lengths(pRes);
- for(i = 0 ;i<num_fields;i++)
- if(pField[i].type == MYSQL_TYPE_STRING && length[i])
- printf("%s %lu bytes\\n",myRow[i],length[i]);
- }
- out:
- if(pRes)
- mysql_free_result(pRes);
- mysql_close(&conn);
- return 0;
- }
- //该片段来自于http://www.codesnippet.cn/detail/180920135996.html
来源: http://www.codesnippet.cn/detail/180920135996.html