#include <mysql.h>
#include <stdio.h>
#include "stack-c.h"

MYSQL mysql;
int connflag=2;	//0:connect success 
			//1:connect fail
			//2:not connect

_declspec(dllexport) void sql_connect(char *host,char *user,char *passwd,char *db,int *conn)
{
	mysql_init(&mysql);
	if(!mysql_real_connect(&mysql,host,user,passwd,db,0,NULL,0))
		{*conn=1;
		connflag=1;
		MessageBox(NULL,"connect Mysql failure","connect Mysql failure",MB_OK);
		}
	else 	
	{*conn=0;
	connflag=0;
	MessageBox(NULL,"connect Mysql success","connect Mysql success",MB_OK);
	}		
}



_declspec(dllexport) void sql_query(char *query,char result[100][100],int *error)
{
	MYSQL_RES *res;
	MYSQL_ROW row;
	int l,t,h,c;             		//l->columns h->rows t->database operation error flag
	h=0;
	c=0;
	*error=0;
//	*query="SELECT * FROM tabletest t";	
	if(!connflag)
  	{
		mysql_ping(&mysql);
		t=mysql_real_query(&mysql,query,(unsigned int)strlen(query));

		//if t=0 Database operation successful
		if(!t)					
		{
			res=mysql_use_result(&mysql);
			if(res != NULL)
			{	      
					c=mysql_num_fields(res);
					while(row=mysql_fetch_row(res))
   					{
					//	strcpy(result,row[1]);
	   					for(l=0;l<c;l++)
						{
						strcpy(result[l],row[1]);
					//		strcat(result,row[l]);
						}
						//'\n'
						h++;
   					}
				//	result=r;
				//	strcpy(*result,"11");
				mysql_free_result(res);
			}              //not SELECT, SHOW operations and so on*/
//			result=res;
			mysql_free_result(res);
		}
		else *error=1;                      //query fail
	}
	else *error=2;					//not connect or connect fail
	
}



_declspec(dllexport) void sql_close()
{
	if(connflag==0)
		mysql_close(&mysql);
	connflag=2;
}


