
#include <stdio.h>
#include <unistd.h> //for getopt
#include <string.h>
#include <mysql.h>
 
#define MAINTITLE "MySQL Demo"
static const char note[] = ""
MAINTITLE"\n"
"Options:\n"
"-s serverip    Specify the ip address of MySQL Server\n"
"-u username    Specify the user name of MySQL Server\n"
"-p password    Specify the password of MySQL Server\n"
"-d database    Specify the database of MySQL Server\n"
"-t tableset    Specify the tableset of MySQL Server\n"
"-h             Display this help and exit\n";

void print_usage(char *pname)
{
	printf("\nUsage: %s [OPTION] [VALUE] ...\n", pname);
	printf("%s\n", note);
}

int main(int argc, char **argv)
{
	MYSQL *conn;
	MYSQL_RES *res;
	MYSQL_ROW row;
	unsigned int num_fields;
	int i, c;
	char serverip[128];
	char username[128];
	char password[128];
	char database[128];
	char tableset[128];
	char szsqlcmd[128];

	memset(serverip, 0, sizeof(serverip));
	memset(username, 0, sizeof(username));
	memset(username, 0, sizeof(username));
	memset(database, 0, sizeof(database));
	memset(tableset, 0, sizeof(tableset));

	while((c=getopt(argc, argv, "s:u:p:d:t:h")) != -1)
	{
		switch(c)
		{
			case 's':
				//baudrate = atol(optarg);
				strncpy(serverip, optarg, sizeof(serverip));
				break;
			case 'u':
				strncpy(username, optarg, sizeof(username));
				break;
			case 'p':
				strncpy(password, optarg, sizeof(password));
				break;
			case 'd':
				strncpy(database, optarg, sizeof(database));
				break;
			case 't':
				strncpy(tableset, optarg, sizeof(tableset));
				break;
			case 'h':
				print_usage(argv[0]);
				return 0; 
				break;
		}
	}

	conn = mysql_init(NULL);
	/* Connect to database */
	if (!mysql_real_connect(conn, 
		serverip[0]?serverip:NULL,
		username[0]?username:NULL, 
		password[0]?password:NULL,
		database[0]?database:NULL, 0, NULL, 0)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		return 1;
	}
	/* send SQL query */
	if (mysql_query(conn, "show tables")) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		return 1;
	}
	printf("MySQL Tables in database %s:\n", database);
	res = mysql_use_result(conn);
	while ((row = mysql_fetch_row(res)) != NULL) {
		printf("%s \n", row[0]);
	}
	mysql_free_result(res);

	if(tableset[0]) {
		snprintf(szsqlcmd, sizeof(szsqlcmd), "select * from %s", tableset);
		if (mysql_query(conn, szsqlcmd)) {
			fprintf(stderr, "%s\n", mysql_error(conn));
			return 1;
		}
		res = mysql_use_result(conn);
		num_fields = mysql_num_fields(res);
		printf("There is %d row in %s table of %s database:\n", num_fields, tableset, database);
		while ((row = mysql_fetch_row(res)) != NULL) {
			unsigned long *lengths;
			lengths = mysql_fetch_lengths(res);
			for(i = 0; i < num_fields; i++)
			{
				printf("[%.*s] ", (int) lengths[i], row[i] ? row[i] : "NULL");
			}
			printf("\n");
		}
	}
	/* close connection */
	mysql_close(conn);
	return 0;
}
