vc连接mysql

官方网站

http://dev.mysql.com/doc/refman/5.7/en/c-api-function-overview.html


#include <iostream.h>
#include <stdio.h>
#include <windows.h>
#include <mysql.h>

int main()
{
	MYSQL mysql;
	MYSQL_RES *result;
	MYSQL_FIELD *fields;
	MYSQL_ROW rows;

	int numOfRows, numOfFields;

	mysql_init(&mysql);

	if (!mysql_real_connect(&mysql,"127.0.0.1","root","","bi",0,NULL,0)){
		fprintf(stderr, "Failed to connect to database: Error: %s\n",
			mysql_error(&mysql));

		return -1;
	}

	printf("MYSQL VERSON IS : %s\n",mysql_get_server_info(&mysql));

	mysql_set_character_set(&mysql, "gbk");

	if (!mysql_query(&mysql,"SELECT * FROM trans_05 LIMIT 0 , 10 ")){
		result = mysql_store_result(&mysql);
		while (fields = mysql_fetch_field(result)){
			printf("%s\t",fields->name);
		}
		printf("\n");

		numOfFields = mysql_num_fields(result);

		while (rows = mysql_fetch_row(result)){
			for (int i=0; i<numOfFields; i++){
				printf("%s\t",rows[i]);
			}
			printf("\n");
		}

		numOfRows = (int)mysql_num_rows(result);
		printf("%d rows fetch.\n",numOfRows);

		mysql_free_result(result);


	}else{
		printf("select error : %s\n",mysql_error(&mysql));
	}

	mysql_close(&mysql);

	return 0;
}


posted on 2016-07-25 16:24  阮減显  阅读(130)  评论(0编辑  收藏  举报

导航