int CMySQLDynamicRecordSet::Init(CMySQLConnection * pDBConnection,MYSQL_STMT_HANDLE hStmt)
{
	if(pDBConnection==NULL||hStmt==NULL)
		return DBERR_INVALID_PARAM;
	Destory();
	m_pDBConnection=pDBConnection;
	m_hStmt=hStmt;
	MYSQL_RES_HANDLE hResult=mysql_stmt_result_metadata(m_hStmt);
	if(hResult==NULL)
	{
		return DBERR_NO_RECORDS;
	}
	int ColNum=mysql_num_fields(hResult);
	m_pColumnInfos.Resize(ColNum);
	m_RowBuffer.Resize(ColNum);
	m_FetchBuffer.Resize(ColNum);	
	ZeroMemory(&(m_FetchBuffer[0]),sizeof(MYSQL_BIND)*ColNum);
	MYSQL_FIELD * pFields=mysql_fetch_fields(hResult);
	UINT FetchBufferLen=0;
	for(int i=0;i<ColNum;i++)
	{
		UINT Size=pFields[i].length;
		UINT DigitalSize=pFields[i].decimals;
		int DBType=CMySQLConnection::MySQLTypeToDBLibType(pFields[i].type,Size,DigitalSize);
		strncpy_0(m_pColumnInfos[i].Name,MAX_COLUMN_NAME,pFields[i].name,MAX_COLUMN_NAME);		
		m_pColumnInfos[i].Type=DBType;
		m_pColumnInfos[i].Size=Size;
		m_pColumnInfos[i].DigitSize=DigitalSize;		
		FetchBufferLen+=CMySQLConnection::GetMySQLTypeBinLength(pFields[i].type,pFields[i].length,pFields[i].decimals)+sizeof(UINT)+sizeof(my_bool);
	}
	m_FetchDataBuffer.Create(FetchBufferLen);
	for(int i=0;i<ColNum;i++)
	{	
		m_FetchBuffer[i].buffer_type=pFields[i].type;
		m_FetchBuffer[i].is_unsigned=(pFields[i].flags&UNSIGNED_FLAG)?1:0;
		m_FetchBuffer[i].buffer=(char *)m_FetchDataBuffer.GetFreeBuffer();
		m_FetchBuffer[i].buffer_length=CMySQLConnection::GetMySQLTypeBinLength(pFields[i].type,pFields[i].length,pFields[i].decimals);
		m_FetchDataBuffer.PushBack(NULL,m_FetchBuffer[i].buffer_length);		

		m_FetchBuffer[i].length=(ULONG *)m_FetchDataBuffer.GetFreeBuffer();
		m_FetchDataBuffer.PushConstBack(m_pColumnInfos[i].Size,sizeof(ULONG));

		m_FetchBuffer[i].is_null=(my_bool *)m_FetchDataBuffer.GetFreeBuffer();
		m_FetchDataBuffer.PushConstBack(0,sizeof(my_bool));

		
	}
	mysql_free_result(hResult);

	if(mysql_stmt_bind_result(m_hStmt,&(m_FetchBuffer[0])))
	{
		m_pDBConnection->ProcessErrorMsg(m_hStmt,"绑定结果集失败");
		return DBERR_BINDCOLFAIL;
	}
	if(m_CacheAllData)
	{
		if(mysql_stmt_store_result(m_hStmt))
		{
			m_pDBConnection->ProcessErrorMsg(m_hStmt,"缓存结果集失败");
			return DBERR_BUFFER_OVERFLOW;
		}
	}
	int Ret=FetchRow();	
	return Ret;
}
Exemple #2
0
int db_address2admcode(OPW_HEADER *hd, char *city, char *gu, char *dong, char *admcode)
{
	int ret = E_NO_ERR ;
	char sql[SQL_SIZE] = {'\0'} ;

	int i, cnt = 0, n;
	MYSQL *conn = NULL ;
	MYSQL_RES *res_set = NULL ;
	MYSQL_ROW row = NULL ;

	conn = mysql_init(NULL) ;
	if(mysql_real_connect(conn, Config.DB_HOST, 
			Config.DB_USER, Config.DB_PASSWORD, Config.DB_NAME, atoi(Config.DB_PORT), NULL, 0) == NULL) {
		printLog(HEAD, "ERR: mysql_real_connect\n") ;
		ret = E_NOT_CONN_DB ;
		goto error_exit ;
	}

	memset(sql, 0, sizeof(sql)) ;
	if(strlen(city) && strlen(gu) && strlen(dong) ) {
		sprintf(sql, "select DISTINCT DONG_CODE from T_ADMCODE where "
				"SI_NAME='%s' and GU_NAME='%s' and DONG_NAME like '%%%s%%'", city, gu, dong) ;
	}
	else if(strlen(city) && strlen(gu)) {
		sprintf(sql, "select DISTINCT GU_CODE from T_ADMCODE where "
				"SI_NAME='%s' and GU_NAME='%s'", city, gu) ;
	}
	else if(strlen(city)) {
		sprintf(sql, "select DISTINCT SI_CODE from T_ADMCODE where "
				"SI_NAME='%s'", city) ;
	}
	else {
		goto error_exit ;
	}
	printLog(HEAD, "(%d) sql(%s)\n", hd->mdn, sql) ;

	ret = mysql_query(conn, sql) ;
	if(ret == DB_SUCCESS) {
		res_set = mysql_store_result(conn) ;
		if(res_set == NULL) ret = E_BAD_SQL ;
		else cnt = (int) mysql_num_rows(res_set) ;
	}

	if(ret != DB_SUCCESS) {
		printLog(HEAD, "ERR: (%d) mydbc_exectue_get_result:[%d]\n", hd->mdn, ret);
		ret = E_BAD_SQL ;
		goto error_exit ;
	}
    if(cnt == 0) {
	    printLog(HEAD, "ERR: (%d) Not Exist admcode(%s)\n", hd->mdn, admcode) ;
        ret = E_NO_DATA ;
        goto error_exit ;
    }

	for(i = 0; i<cnt; i++) {
		if((row = mydbc_next_row(&res_set)) == NULL) break;
		n = -1;
		if(row[++n] != NULL) strncpy(admcode, row[n], D_ADMCODE_SIZE);
	}

error_exit :
	mysql_free_result(res_set) ;

	mysql_close(conn) ;

	return ret ;
}
Exemple #3
0
int db_opw_list(OPW_HEADER *hd, OPW_LIST_REQ *req, OPW_RESULT *rd, OPW_LIST_INFO **out)
{
	int ret = E_NO_ERR ;
	
	char sql[SQL_SIZE] = {'\0'} ;
	char where_oiltype[200] = {'\0'} ;
	char where_search_opt[200] = {'\0'} ;
	char where_pole[300] = {'\0'} ;
	char where_sort_opt[200] = {'\0'} ;
	char where_time[200] = {'\0'} ;

	char admcode[D_ADMCODE_SIZE+1] = "" ;
	char fmcode[D_FMCODE_SIZE+1] = "" ;
	char gn_time[D_GN_TIME_SIZE+1] = "" ;

	int sido_flag = 0 ; 
	int gugun_flag = 0 ;
	int dong_flag = 0 ;

	int i, n, cnt = 0 ;
	int valid_cnt = 0 ;
	int k = 0 ;

	MYSQL *conn = NULL ;
	MYSQL_RES *res_set = NULL ;
	MYSQL_ROW row = NULL ;

	OPW_LIST_INFO *data = NULL ;
	int fetch_count = 0 ;

	OPW_LIST_INFO *buf = NULL ;

	time_t tt ;

//	ret = mydbc_init(&conn);
//	if(ret != DB_SUCCESS) {
//		printLog(HEAD, "ERR: mydbc_init[%d]\n", ret);
//		ret = E_NOT_CONN_DB ;
//		goto error_exit ;
//	}
	conn = mysql_init(NULL) ;
	if(mysql_real_connect(conn, Config.DB_HOST, 
			Config.DB_USER, Config.DB_PASSWORD, Config.DB_NAME, atoi(Config.DB_PORT), NULL, 0) == NULL) {
		printLog(HEAD, "ERR: mysql_real_connect\n") ;
		ret = E_NOT_CONN_DB ;
		goto error_exit ;
	}	
//	if(mysql_query(conn, "set names utf8")){
//		printLog(HEAD, "ERR: mysql query error:%s", mysql_error(conn)) ;
//	}

	//: 입력 오류 체크
	if(check_option(hd, req)) {
		ret = E_NO_DATA ;
		goto error_exit ;
	}
	
	memset(sql, 0, sizeof(sql)) ;

	switch(hd->oil_type) {
		case 'A' :	//: 모든 종류
		//	sprintf(where_oiltype, "and (g_price>100 or k_price>100 or d_price>100 or l_price>100) ") ;
			sprintf(where_oiltype, "and (GN_PRICE>100 or DN_PRICE>100 or GP_PRICE>100 or LPG_PRICE>100) ") ;
		//	make_where_oiltype(req->pole, where_oiltype) ;
			break ;
		case 'G' :	//: 휘발유
		//	sprintf(where_oiltype, "and (g_price>100) ") ;
			sprintf(where_oiltype, "and (GN_PRICE>100) ") ;
		//	make_where_oiltype(req->pole, where_oiltype) ;
			break ;
		case 'K' : 	//: 경유
		//	sprintf(where_oiltype, "and (k_price>100) ") ;
			sprintf(where_oiltype, "and (DN_PRICE>100) ") ;
		//	make_where_oiltype(req->pole, where_oiltype) ;
			break ;
		case 'D' :	//: 등유
		//	sprintf(where_oiltype, "and (GP_PRICE>100) ") ;
			break ;
		case 'L' : 	//: LPG
			sprintf(where_oiltype, "and (LPG_PRICE>100) ") ;
		//	make_where_oiltype(req->pole, where_oiltype) ;
			break ;
		default :
			break ;
	}

	switch(hd->search_opt[0]) {
		case 'A' :	//: 좌표로 검색
		//	sprintf(where_search_opt, "and (map_x > '%d' and map_x < '%d' and map_y > '%d' and map_y < '%d') ", 
			sprintf(where_search_opt, "and (XPOS > %d and XPOS < %d and YPOS > %d and YPOS < %d) ", 
					(req->x - req->radius), (req->x + req->radius), (req->y - req->radius), (req->y + req->radius)) ;
			break ;
		case 'I' :	//: 주소로 검색

		//	if(strlen(req->sido)>0) sido_flag = 1 ;
		//	if(strlen(req->gugun)>0) gugun_flag = 1 ;
		//	if(strlen(req->dong)>0) dong_flag = 1 ;

		//	if((sido_flag == 1) && (gugun_flag == 1) && (dong_flag == 1))
		//		sprintf(where_search_opt, "and (sido='%.16s' and gugun='%.32s' and dong like '%%%.52s%%') ", 
		//				req->sido, req->gugun, req->dong) ;
		//	else if((sido_flag == 1) && (gugun_flag == 1) && (dong_flag == 0))
		//		sprintf(where_search_opt, "and (sido='%.16s' and gugun='%.32s') ", req->sido, req->gugun) ;
		//	else if((sido_flag == 1) && (gugun_flag == 0) && (dong_flag == 0))
		//		sprintf(where_search_opt, "and (sido='%.16s')  ", req->sido) ;
			db_address2admcode(hd, req->sido, req->gugun, req->dong, admcode) ;
			sprintf(where_search_opt, "and (ADMCODE like '%s%%') ", admcode) ;

			break ;
		case 'U' :	//: 국도(상)로 검색
		//	sprintf(where_search_opt, "and (type_way=%d and updown='L') ", req->nr_num+100) ;
			break ;
		case 'D' :	//: 국도(하)로 검색
		//	sprintf(where_search_opt, "and (type_way=%d and updown = 'R') ", req->nr_num+100) ;
			break ;
		default :
			break ;
	}

	if(req->pole != 0) {
		//: pole=7: SK-gas  pole=8: LG-gas
		//	if((req->pole == 7) || (req->pole == 8)) sprintf(where_pole, "and (pole=7 or pole=8) ") ;
	//	if((req->pole == 7) || (req->pole == 8)) sprintf(where_pole, "and (jcomp=1 or jcomp=2) ") ;
	//	else if(req->pole <= 6) {
	//		if(req->pole == 1) sprintf(where_pole, "and (pole=1 or pole=14) ") ;
	//		else sprintf(where_pole, "and (pole=%d) ", req->pole) ;
	//	}
	//	else {
	//	}
		make_where_pole(req->pole, where_pole) ;
		printLog(HEAD, "DEBUG: where_pole[%s]\n", where_pole) ;
	}

	switch(req->sort_opt) {
		case 1 : 	//: 휘발유 가격으로 오름차순
		//	sprintf(where_sort_opt, "and (g_price > 0 ) order by g_price asc") ;
			sprintf(where_sort_opt, "and (GN_PRICE > 0 ) order by GN_PRICE asc") ;
			break ;
		case 2 : 	//: 경유 가격으로 오름차순
		//	sprintf(where_sort_opt, "and (k_price > 0) order by k_price asc") ;
			sprintf(where_sort_opt, "and (DN_PRICE > 0) order by DN_PRICE asc") ;
			break ;
		case 3 :	//: 등유 가격으로 오름차순
		//	sprintf(where_sort_opt, "and (d_price > 0) order by d_price asc") ;
		//	sprintf(where_sort_opt, "and (GP_PRICE > 0) order by GP_PRICE asc") ;
			break ;
		case 4 :	//: LPG 가격으로 오름차순
		//	sprintf(where_sort_opt, "and (l_price > 0) order by l_price asc") ;
			sprintf(where_sort_opt, "and (LPG_PRICE > 0) order by LPG_PRICE asc") ;
			break ;
		case 6 : 	//: 휘발유>경유>등유>LPG 오름차순
		//	sprintf(where_sort_opt, "order by g_price, k_price, d_price, l_price asc") ;
			sprintf(where_sort_opt, "order by GN_PRICE, DN_PRICE, LPG_PRICE asc") ;
			break ;
		default :
			break ;
	}

//	sprintf(sql, "select j_id, jname, pole, g_price, k_price, d_price, l_price, "
//			"date_format(update_time, '%%Y%%m%%d'), date_format(update_time, '%%H%%i%%s'), "
//			"map_x, map_y from TSmain where (update_time > date_add(now(), interval -1 month)) %s %s %s %s", 
//			where_oiltype, where_search_opt, where_pole, where_sort_opt) ;

	tt = time(&tt) ;
	tt -= (3600 * 24) * 30 ;	//약 30일 이전 시간 구함

	memset(gn_time, 0, sizeof(gn_time)) ;
	time2TimeStr(tt, gn_time) ;

	make_where_time(hd, where_time, gn_time) ; 

	sprintf(sql, "select POI_ID, NAME, FMCODE, GN_PRICE, DN_PRICE, LPG_PRICE, "
			"GN_TIME, "
			"XPOS, YPOS from T_OIL_SERVICE where (%s) %s %s %s %s", 
			where_time, where_oiltype, where_search_opt, where_pole, where_sort_opt) ;
	printLog(HEAD, "sql(%s)\n", sql) ;

//	ret = mydbc_execute_get_result(&conn, sql, &cnt, &res_set);
	ret = mysql_query(conn, sql) ;
	if(ret == DB_SUCCESS) {
		res_set = mysql_store_result(conn) ;
		if(res_set == NULL) ret = E_BAD_SQL ;
		else cnt = (int) mysql_num_rows(res_set) ;
	}

	if(ret != DB_SUCCESS) {
		if(data != NULL) free(data), data=NULL ;
		ret = E_BAD_SQL ;
		goto error_exit ;
	}

	if(cnt == 0) {
		printLog(HEAD, "ERR: (%d) NO DATA ABOUT T_OIL_SERVICE\n", hd->mdn) ;
		ret = E_NO_DATA ;
		goto error_exit ;
	}

	if((buf = (OPW_LIST_INFO *) malloc (sizeof(OPW_LIST_INFO) * cnt)) == NULL) {
		printLog(HEAD, "ERR: Fatal Memory Alloc Fail\n") ;
		ret = E_MEM_ALLOC ;
		goto error_exit ;
	}
	memset(buf, 0, sizeof(OPW_LIST_INFO) * cnt) ;

	for(i = 0 ; i < cnt ; i++) {
		if((row = mydbc_next_row(&res_set)) == NULL) break;
		n = -1;
		if(row[++n] != NULL) buf[i].id = atoi(row[n]) ;
		if(row[++n] != NULL) strncpy(buf[i].name, row[n], D_NAME_SIZE) ;
		//--
	//	if(row[++n] != NULL) buf[i].pole = atoi(row[n]) ;
		memset(fmcode, 0, sizeof(fmcode)) ;
		if(row[++n] != NULL) strncpy(fmcode, row[n], D_FMCODE_SIZE) ;
		buf[i].pole = fmcode2pole(fmcode) ;

	//	printLog(HEAD, "DEBUG: fmcode[%s]==>pole(%d)\n", fmcode, buf[i].pole) ;

		//--	
	//	if(buf[i].pole == 14) buf[i].pole = 1 ;		//: SK인천정유 주유소(14)->SK(1)
	//	if(buf[i].pole == 15) buf[i].pole = 7 ;		//: SK인천 GAS(15)->SK GAS(7)	

		
		if(row[++n] != NULL) {
			buf[i].g_price = atoi(row[n]) ;
			if((req->sort_opt == 6) && (buf[i].g_price == 0)) buf[i].g_price = ZERO_MAX_CONV ;
		}
		if(row[++n] != NULL) {
			buf[i].k_price = atoi(row[n]) ;
			if((req->sort_opt == 6) && (buf[i].k_price == 0)) buf[i].k_price = ZERO_MAX_CONV ;
		}
	//	if(row[++n] != NULL) {		//등유는 정보 없음으로 제거
	//		buf[i].d_price = atoi(row[n]) ;
	//		if((req->sort_opt == 6) && (buf[i].d_price == 0)) buf[i].d_price = ZERO_MAX_CONV ;
	//	}
		if(row[++n] != NULL) {
			buf[i].l_price = atoi(row[n]) ;
			if((req->sort_opt == 6) && (buf[i].l_price == 0)) buf[i].l_price = ZERO_MAX_CONV ;
		}
		//-
	//	if(row[++n] != NULL) buf[i].update_date = atoi(row[n]) ;
	//	if(row[++n] != NULL) buf[i].update_time = atoi(row[n]) ;
		memset(gn_time, 0, sizeof(gn_time)) ;
		if(row[++n] != NULL) strncpy(gn_time, row[n], D_GN_TIME_SIZE) ;
		timeStr2DateTime(gn_time, &(buf[i].update_date), &(buf[i].update_time)) ;	
	//	printLog(HEAD, "DEBUG: update_date(%d) update_time(%d)\n", buf[i].update_date, buf[i].update_time) ;
		//-
		if(row[++n] != NULL) buf[i].x = atoi(row[n]) ;
		if(row[++n] != NULL) buf[i].y = atoi(row[n]) ;

		//: 좌표로 검색인 경우
		if(hd->search_opt[0]=='A') {
			buf[i].distance = get_distance(req->x, req->y, buf[i].x, buf[i].y) ;
		}

		//: 2007-05-28 valid data구함
		if((buf[i].x != 0) && (buf[i].y != 0)) valid_cnt++ ;
	}

	//: if MsgId=1060 and search_opt[0]='I' 
	//:		then hd->Oil_type에 따라 OPW_LIST_INFO 필드 내용 변경(INAVI APP의 오류로 인한 특정CASE임)
	if((hd->serviceid == OPW_LIST) && (hd->search_opt[0]=='I'))
		conv_opw_list(hd, buf, cnt) ;

	if(req->sort_opt == 6) {
		qsort(buf, cnt, sizeof(OPW_LIST_INFO), sort_comp) ;

		for(i = 0 ; i <cnt ; i++) {
			if(buf[i].g_price == ZERO_MAX_CONV) buf[i].g_price = 0 ;
			if(buf[i].k_price == ZERO_MAX_CONV) buf[i].k_price = 0 ;
			if(buf[i].d_price == ZERO_MAX_CONV) buf[i].d_price = 0 ;
			if(buf[i].l_price == ZERO_MAX_CONV) buf[i].l_price = 0 ;

			printLog(HEAD, "[%d] id(%d)name(%.52s)pole(%d)g(%d)k(%d)d(%d)l(%d)date(%d)time(%d)x(%d)y(%d)distance(%d)\n",
					i, buf[i].id, buf[i].name, buf[i].pole, 
					buf[i].g_price, buf[i].k_price, buf[i].d_price, buf[i].l_price, 
					buf[i].update_date, buf[i].update_time, 
					buf[i].x, buf[i].y, buf[i].distance) ;
		}
	}

	//: 좌표로 검색인 경우이고 거리로 오름차순일때
	if((hd->search_opt[0]=='A') && (req->sort_opt == 5)) {
		qsort(buf, cnt, sizeof(OPW_LIST_INFO), (int (*)(const void *, const void *)) cmp_string_up) ;
	}

	//: 최종 검색 데이타
	printLog(HEAD, "(%d): cnt(%d) valid_cnt[%d] req->start_pos(%d) req->search_num(%d)\n", 
			hd->mdn, cnt, valid_cnt, req->start_pos, req->search_num) ;

	//: 2007-05-28 valid한 데이타로 fetch count구함
//	if(cnt <= (req->start_pos)) {
	if(valid_cnt <= (req->start_pos)) {
		printLog(HEAD, "ERR: (%d) NO DATA(cnt:%d-valid_cnt:%d) more than start(%d)\n", 
				hd->mdn, cnt, valid_cnt, req->start_pos) ;
		ret = E_NO_DATA ;
		goto error_exit ;
	}

//	if((cnt - (req->start_pos)) < req->search_num) fetch_count = cnt - (req->start_pos) ;
	if((valid_cnt - (req->start_pos)) < req->search_num) fetch_count = valid_cnt - (req->start_pos) ;
	else fetch_count = req->search_num ;

	printLog(HEAD, "DEBUG: fetch_count(%d)\n", fetch_count) ;

	if((data = (OPW_LIST_INFO *) malloc (sizeof(OPW_LIST_INFO) * fetch_count)) == NULL) {
		printLog(HEAD, "ERR: Fatal Memory Alloc Fail\n") ;
		ret = E_MEM_ALLOC ;
		goto error_exit ;
	}
	memset(data, 0, sizeof(OPW_LIST_INFO) * fetch_count) ;

//	for(i= 0, n=0 ; (i < fetch_count) && (n < cnt) ; n++) {
	for(i= 0, n=0 ; n < cnt ; n++) {

		// 2007-05-28 예외 사항 추가
		// x가 0 또는 y=0이면 패스
		if((buf[n].x == 0) || (buf[n].y == 0)) {
			k++ ;
			continue ;
		}

		if(n < (req->start_pos + k)) continue ;
		else if(n >= (req->start_pos+fetch_count+k)) continue ;

		memcpy(&data[i], &buf[n], sizeof(OPW_LIST_INFO)) ;
		printLog(HEAD, "[%d] id(%d)name(%.52s)pole(%d)g(%d)k(%d)d(%d)l(%d)date(%d)time(%d)x(%d)y(%d)distance(%d)\n",
			i, data[i].id, data[i].name, data[i].pole, 
			data[i].g_price, data[i].k_price, data[i].d_price, data[i].l_price, 
			data[i].update_date, data[i].update_time, 
			data[i].x, data[i].y, data[i].distance) ;

		data[i].id = htonl(data[i].id) ;
		data[i].pole = htonl(data[i].pole) ;
		if(data[i].g_price < 100) data[i].g_price = 0 ;
		data[i].g_price = htons(data[i].g_price) ;
		if(data[i].k_price < 100) data[i].k_price = 0 ;
		data[i].k_price = htons(data[i].k_price) ;
		if(data[i].d_price < 100) data[i].d_price = 0 ;
		data[i].d_price = htons(data[i].d_price) ;
		if(data[i].l_price < 100) data[i].l_price = 0 ;
		data[i].l_price = htons(data[i].l_price) ;
		data[i].update_date = htonl(data[i].update_date) ;
		data[i].update_time = htonl(data[i].update_time) ;
		data[i].x = htonl(data[i].x) ;
		data[i].y = htonl(data[i].y) ;
		data[i].distance = htonl(data[i].distance) ;
		i++ ;
	}

	*out = data;

error_exit:
//	mydbc_free_result(&res_set) ;
	mysql_free_result(res_set) ;

	if(buf != NULL) free(buf) ;
	buf = NULL ;

	rd->res_code = ret ;
//	rd->total_num = cnt ;
	rd->total_num = valid_cnt ;
	rd->search_num = fetch_count ;

	mysql_close(conn) ;
//	ret = mydbc_end(&conn);
//	if(ret != DB_SUCCESS) {
//		printLog(HEAD, "ERR: mydbc_end[%d]\n", ret);
//	}
	return ret ;
}
Exemple #4
0
void DeleteBook()   /*删除图书信息*/
{
    char id[10];   /*结果集中的行数*/
    char *sql;
    char dest[100] ={"  "};
    char dest1[100] ={"  "};
    if(!mysql_real_connect(&mysql,"127.0.0.1","root","111","db_books",0,NULL,0))
    {
        printf("\t 不能连接数据库!\n");
    }
    else
    {
        printf("\t 请输入您想要删除的图书编号. ");        
        scanf("%s",id);   /*输入图书编号*/
        sql = "select * from tb_book where id=";
        strcat(dest,sql);
        strcat(dest,id);    /*将图书编号追加到sql语句后面*/        
        //printf("%s\n",dest);
        
        /*查询该图书信息是否存在*/
        if(mysql_query(&mysql,dest))
        {   //如果查询失败
            printf("\n 查询 tb_book 数据表失败! \n");
        }
        else
        { 
            result=mysql_store_result(&mysql); //获得结果集
            if(mysql_num_rows(result)!=NULL)
            {  //有记录的情况,只有有记录取数据才有意义
                printf("\t 发现记录信息,是否显示?(y/n) ");
                scanf("%s",ch);
                if(strcmp(ch,"Y")==0||strcmp(ch,"y")==0)/*判断是否要显示查找到的信息*/
                {
                    printf("\t ════════════════════════════ \n");
                    printf("\t               ***** 显示图书信息 *****                   \n");
                    printf("\t ════════════════════════════ \n");
                    printf("\t图书编号       图书名         作者        出版社      \n");
                    printf("\t -------------------------------------------------------- \n");
                    while((row=mysql_fetch_row(result)))
                    {   //取出结果集中记录
                        fprintf(stdout,"\t   %s             %s             %s          %s   \n",row[0],row[1],row[2],row[3]);  //输出这行记录
                    }
                    printf("\t ════════════════════════════ \n");
                }
                                    
                    printf("\t 是否删除?(y/n) ");
                    scanf("%s",ch);
                    if (strcmp(ch,"Y")==0||strcmp(ch,"y")==0)    /*判断是否需要录入*/
                    {
                        sql = "delete from tb_book where ID= ";
                        printf("%s",dest1);
                        strcat(dest1,sql);
                        strcat(dest1,id);
                       // printf("%s",dest1);
                        
                        if(mysql_query(&mysql,dest1)!=0)
                        {
                            fprintf(stderr,"\t 不能删除记录! \n",mysql_error(&mysql));
                        }
                        else
                        {
                            printf("\t 删除成功!\n");
                        }
                    }
            }
            else
            {
                printf("\t 没有发现要删除的信息!\n");
            }
        }
        mysql_free_result(result);    //释放结果集
    }
    mysql_close(&mysql);
    inquire();   /*询问是否显示主菜单*/
}
Exemple #5
0
int 
cmyth_get_bookmark_offset(cmyth_database_t db, long chanid, long long mark, char *starttime, int mode) 
{
	MYSQL_RES *res = NULL;
	MYSQL_ROW row;
	int offset=0;
	int rows = 0;
	int rectype = 0;
	cmyth_mysql_query_t * query;
	
	const char *query_str = "SELECT * FROM recordedseek WHERE chanid = ? AND mark<= ? AND starttime = ? ORDER BY MARK DESC LIMIT 1;";

	query = cmyth_mysql_query_create(db,query_str);
	if (cmyth_mysql_query_param_long(query, chanid) < 0
		|| cmyth_mysql_query_param_long(query, mark) < 0
		|| cmyth_mysql_query_param_str(query, starttime) < 0
		) {
		cmyth_dbg(CMYTH_DBG_ERROR,"%s, binding of query parameters failed! Maybe we're out of memory?\n", __FUNCTION__);
		ref_release(query);
		return -1;
	}
	res = cmyth_mysql_query_result(query);
	ref_release(query);
	if (res == NULL) {
		cmyth_dbg(CMYTH_DBG_ERROR, "%s, finalisation/execution of query failed!\n", __FUNCTION__);
		return -1;
	}
	while ((row = mysql_fetch_row(res))) {
		offset = safe_atoi(row[3]);
		rectype = safe_atoi(row[4]);
		rows++;
	}
	if (rectype != 9) {
		if (mode == 0) {
			mark=(mark/15)+1;
		}
		else if (mode == 1) {
			mark=(mark/12)+1;
		}
		query = cmyth_mysql_query_create(db, query_str);
		if (cmyth_mysql_query_param_long(query, chanid) < 0
			|| cmyth_mysql_query_param_long(query, mark) < 0
			|| cmyth_mysql_query_param_str(query, starttime) < 0
			) {
			cmyth_dbg(CMYTH_DBG_ERROR,"%s, binding of query parameters failed! Maybe we're out of memory?\n", __FUNCTION__);
			ref_release(query);
			return -1;
		}
		res = cmyth_mysql_query_result(query);
		ref_release(query);
		if (res == NULL) {
			cmyth_dbg(CMYTH_DBG_ERROR, "%s, finalisation/execution of query failed!\n", __FUNCTION__);
			return -1;
		}
		while ((row = mysql_fetch_row(res))) {
			offset = safe_atoi(row[3]);
			rows++;
		}
	}
	mysql_free_result(res);
	return offset;
}
void Database::clear(){
    mysql_free_result(qry);
}
Exemple #7
0
void AddBook()    /*添加图书信息*/
{
    int rowcount;   /*结果集中的行数*/
    
    char id[10];       /*编号*/
    char *bookname;
    char *author;
    char *bookconcern;
    
    char *sql;    
    char dest[500] ={"  "};    
    
    /*连接数据库*/
    if(!mysql_real_connect(&mysql,"127.0.0.1","root","111","db_books",0,NULL,0))
    { 
        printf("\n\t 不能连接数据库!\n");
    }
    else
    {
        /*数据库连接成功,插入数据*/   
        printf("\t ════════════════════════════ \n");
        printf("\t                     添 加 图 书 信 息                    \n");
        printf("\t ════════════════════════════ \n");
        if(mysql_query(&mysql,"select * from tb_book"))
        {   //如果查询失败
            printf("\n\t 查询 tb_book 数据表失败!\n");
        }
        else
        {
            result=mysql_store_result(&mysql); //获得结果集
            rowcount=mysql_num_rows(result) ;  //获得行数
            row=mysql_fetch_row(result);       //获取结果集的行  
            
            printf("\t 图书编号:");
            scanf("%s",id);   /*输入图书编号*/    
            
            sql="insert into tb_book (ID,bookname,author,bookconcern) values (";
            strcat(dest,sql);
            strcat(dest,"'");
            strcat(dest,id);
            strcat(dest,"', '");


            if(mysql_num_rows(result)!=NULL)
            {                
                /*判断输入的编号是否存在*/
                do
                {   //存在相同编号
                    if(!strcmp(id,row[0]))
                    {
                      //  printf("%s",row[0]);
                        printf("\n\t 记录存在,按任意键继续!\n");
                        getch();
                        mysql_free_result(result);   /*释放结果集*/ 
                        mysql_close(&mysql);         /*释放连接*/  
                        inquire();   /*询问是否显示主菜单*/
                        return;
                    }
                }while(row=mysql_fetch_row(result));  
            }
            
            bookname = (char*)malloc(50);
            author = (char*)malloc(50);
            bookconcern = (char*)malloc(50);

            
            //不存在相同的编号            
            printf("\t 图书名:");
            scanf("%s",bookname);   /*输入图书名*/
            strcat(dest,bookname);    /*将图书编号追加到sql语句后面*/
            
            printf("\t 作者:");
            scanf("%s",author);    /*输入作者*/
            strcat(dest,"', '");
            strcat(dest,author);
            
            printf("\t 出版社:");
            scanf("%s",bookconcern);    /*输入出版社*/
            strcat(dest,"', '");
            strcat(dest,bookconcern);
            strcat(dest,"')");
            //printf("%s",dest);
            
            if ( mysql_query(&mysql,dest)!=0)   
            {
                fprintf(stderr,"\t 不能插入记录!",mysql_error(&mysql));
            }
            else
            {
                printf("\t 插入成功!\n");                
            }
            mysql_free_result(result);    //释放结果集
        }
        mysql_close(&mysql);          //释放连接
    }
    inquire();   /*询问是否显示主菜单*/
}   
static boolean reset_user_passwd(SSL *ssl_client, boolean is_admin_flag)
{
	char         buffer[BUFFER_LENGTH + 1];
	char         token_name[TOKEN_NAME_LENGTH + 1];
	char         username[USER_NAME_LENGTH + 1];

	MYSQL        *db_conn = NULL;
  	MYSQL_RES    *result  = NULL;
  	MYSQL_ROW    row;
	char         stat[SQL_STATEMENT_LENGTH + 1];
	char	     err_msg[ERR_MSG_LENGTH + 1];

	unsigned int user_or_admin_id;
	char         email_address[EMAIL_ADDRESS_LENGTH + 1];

	char         random_passwd[PASSWD_LENGTH + 1];
	char         random_salt_value[SALT_VALUE_LENGTH + 1];
	char         random_passwd_with_salt_value[PASSWD_LENGTH + SALT_VALUE_LENGTH + 1];
	char         salted_passwd_hash[SHA1_DIGEST_LENGTH + 1];

	// Receive user/admin password resetting information
	if(SSL_recv_buffer(ssl_client, buffer, NULL) == 0)
	{
		fprintf(stderr, "Receiving user/admin password resetting information failed\n");
		goto ERROR;
	}

	// Get a user/admin password resetting information token from buffer
	if(read_token_from_buffer(buffer, 1, token_name, username) != READ_TOKEN_SUCCESS || strcmp(token_name, "username") != 0)
		int_error("Extracting the username failed");

	// Connect the database
	connect_db(&db_conn, DB_IP, DB_USERNAME, DB_PASSWD, DB_NAME);

	// Check for the existence of username
	if(is_admin_flag)
	{
		sprintf(stat, "SELECT admin_id, email_address FROM %s WHERE username LIKE '%s' COLLATE latin1_general_cs", ESA__ADMINS, username);
	}
	else
	{
		sprintf(stat, "SELECT user_id, email_address FROM %s WHERE username LIKE '%s' COLLATE latin1_general_cs", ESA__USERS, username);
	}

	if(mysql_query(db_conn, stat))
  	{
      		sprintf(err_msg, "Error %u: %s\n", mysql_errno(db_conn), mysql_error(db_conn));
      		int_error(err_msg);
  	}

  	result = mysql_store_result(db_conn);
	row = mysql_fetch_row(result);

	// The user/admin does not exist
	if(!row)
	{
		// Send the user/admin password resetting result flag
		write_token_into_buffer("user_or_admin_passwd_resetting_result_flag", "0", true, buffer);
		write_token_into_buffer("error_msg", "User does not exist", false, buffer);

		if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer)))
		{
			fprintf(stderr, "Sending the user/admin password resetting result flag failed\n");
			goto ERROR;
		}

		goto ERROR;
	}

	user_or_admin_id = atoi(row[0]);
	strcpy(email_address, row[1]);

	if(result)
	{
		mysql_free_result(result);
		result = NULL;
	}

	// Generate a random 8 character password
	gen_random_password(random_passwd);

	// Generate a random 8 character salt value
	gen_random_salt_value(random_salt_value);

	// Get the salted password hash
	sprintf(random_passwd_with_salt_value, "%s%s", random_passwd, random_salt_value);
	sum_sha1_from_string(random_passwd_with_salt_value, strlen(random_passwd_with_salt_value), salted_passwd_hash, SALTED_PASSWD_HASH_PATH);

	// Update the password hash information
	if(is_admin_flag)
	{
		sprintf(stat, "UPDATE %s SET salted_passwd_hash = '%s', salt_value = '%s' WHERE admin_id = %u", 
			ESA__ADMINS, salted_passwd_hash, random_salt_value, user_or_admin_id);
	}
	else
	{
		sprintf(stat, "UPDATE %s SET salted_passwd_hash = '%s', salt_value = '%s' WHERE user_id = %u", 
			ESA__USERS, salted_passwd_hash, random_salt_value, user_or_admin_id);
	}

	if(mysql_query(db_conn, stat))
	{
	      	sprintf(err_msg, "Error %u: %s\n", mysql_errno(db_conn), mysql_error(db_conn));
	      	int_error(err_msg);
	}

	// Generate an SSL certificate
	generate_ssl_cert(db_conn, user_or_admin_id, username, is_admin_flag, random_passwd, email_address, SSL_CERT_PRIV_KEY_PATH, SSL_CERT_REQ_PATH, ENC_SSL_CERT_PATH, 
		FULL_ENC_SSL_CERT_PATH, FULL_ENC_SSL_CERT_HASH_PATH);

	disconnect_db(&db_conn);

	// Lock an e-mail sending
	if(sem_wait(&email_sending_lock_mutex) != 0)
		int_error("Locking the mutex failed");

	if(!send_passwd_to_user_email_address(email_address, username, is_admin_flag, random_passwd))
	{
		// Send the user/admin password resetting result flag
		write_token_into_buffer("user_or_admin_passwd_resetting_result_flag", "0", true, buffer);
		write_token_into_buffer("error_msg", get_send_email_error_msg(), false, buffer);

		// Unlock an e-mail sending
		if(sem_post(&email_sending_lock_mutex) != 0)
			int_error("Unlocking the mutex failed");

		if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer)))
		{
			fprintf(stderr, "Sending the user/admin password resetting result flag failed\n");
			goto ERROR;
		}

		goto ERROR;
	}

	// Unlock an e-mail sending
	if(sem_post(&email_sending_lock_mutex) != 0)
		int_error("Unlocking the mutex failed");

	// Send the user/admin password resetting result flag
	write_token_into_buffer("user_or_admin_passwd_resetting_result_flag", "1", true, buffer);
	if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer)))
	{
		fprintf(stderr, "Sending the user/admin password resetting result flag failed\n");
		goto ERROR;
	}

	return true;

ERROR:

	if(result)
	{
		mysql_free_result(result);
		result = NULL;
	}

	disconnect_db(&db_conn);
	return false;
}
static boolean remove_user(SSL *ssl_client, boolean is_admin_flag)
{
	char         buffer[BUFFER_LENGTH + 1];
	char         token_name[TOKEN_NAME_LENGTH + 1];
	char         username[USER_NAME_LENGTH + 1];

	MYSQL        *db_conn = NULL;
  	MYSQL_RES    *result  = NULL;
  	MYSQL_ROW    row;
	char         stat[SQL_STATEMENT_LENGTH + 1];
	char	     err_msg[ERR_MSG_LENGTH + 1];

	unsigned int user_or_admin_id;

	// Receive user/admin removal information
	if(SSL_recv_buffer(ssl_client, buffer, NULL) == 0)
	{
		fprintf(stderr, "Receiving user/admin removal information failed\n");
		goto ERROR;
	}

	// Get a user/admin removal information token from buffer
	if(read_token_from_buffer(buffer, 1, token_name, username) != READ_TOKEN_SUCCESS || strcmp(token_name, "username") != 0)
		int_error("Extracting the username failed");

	// Connect the database
	connect_db(&db_conn, DB_IP, DB_USERNAME, DB_PASSWD, DB_NAME);

	// Check for the existence of username
	if(is_admin_flag)
	{
		sprintf(stat, "SELECT admin_id FROM %s WHERE username LIKE '%s' COLLATE latin1_general_cs", ESA__ADMINS, username);
	}
	else
	{
		sprintf(stat, "SELECT user_id FROM %s WHERE username LIKE '%s' COLLATE latin1_general_cs", ESA__USERS, username);	
	}

	if(mysql_query(db_conn, stat))
  	{
      		sprintf(err_msg, "Error %u: %s\n", mysql_errno(db_conn), mysql_error(db_conn));
      		int_error(err_msg);
  	}

  	result = mysql_store_result(db_conn);
	row = mysql_fetch_row(result);

	// The user/admin does not exist
	if(!row)
	{
		// Send the user/admin removal result flag
		write_token_into_buffer("user_or_admin_removal_result_flag", "0", true, buffer);
		write_token_into_buffer("error_msg", "User does not exist", false, buffer);

		if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer)))
		{
			fprintf(stderr, "Sending the user/admin removal result flag failed\n");
			goto ERROR;
		}

		goto ERROR;
	}

	user_or_admin_id = atoi(row[0]);

	if(result)
	{
		mysql_free_result(result);
		result = NULL;
	}

	// Delete the user/admin
	if(is_admin_flag)
	{
		sprintf(stat, "DELETE FROM %s WHERE admin_id = %u", ESA__ADMINS, user_or_admin_id);
	}
	else
	{
		sprintf(stat, "DELETE FROM %s WHERE user_id = %u", ESA__USERS, user_or_admin_id);
	}

	if(mysql_query(db_conn, stat))
	{
		sprintf(err_msg, "Error %u: %s\n", mysql_errno(db_conn), mysql_error(db_conn));
		int_error(err_msg);
	}

	disconnect_db(&db_conn);

	// Send the user/admin removal result flag
	write_token_into_buffer("user_or_admin_removal_result_flag", "1", true, buffer);

	if(!SSL_send_buffer(ssl_client, buffer, strlen(buffer)))
	{
		fprintf(stderr, "Sending the user/admin removal result flag failed\n");
		goto ERROR;
	}

	return true;

ERROR:

	if(result)
	{
		mysql_free_result(result);
		result = NULL;
	}

	disconnect_db(&db_conn);
	return false;
}
Exemple #10
0
void sendNicks(int sd, char *buff) {
    char email[GP_EMAIL_LEN];
    char pass[GP_PASSWORD_LEN];
    char query[1024];
    char gamename[32];
    bool sendUnique = false;
    if(!find_param("email", buff, email, sizeof(email))) {
       sendError(sd,"Error recieving request");
       return;	
    }
    if(find_param("gamename", buff, gamename, sizeof(gamename))) {
       sendUnique = true;//just assume you want it sent
    }
    if(!find_param("pass", buff, pass, sizeof(pass))) {
	if(!find_param("passenc",buff,pass,sizeof(pass))) {
	       sendError(sd,"Error recieving request");
	       return;	
	} else {
		char *dpass;
		int passlen = strlen(pass);
		dpass = (char *)base64_decode((uint8_t *)pass, &passlen);
        	passlen = gspassenc((uint8_t *)dpass);
		strcpy(pass,dpass);
		free(dpass);
	}
   }
   mysql_real_escape_string(conn,email,email,strlen(email));
   mysql_real_escape_string(conn,pass,pass,strlen(pass));
   sprintf_s(query,sizeof(query),"SELECT  `nick`,`uniquenick` FROM  `GameTracker`.`users` INNER JOIN  `GameTracker`.`profiles` ON  `GameTracker`.`profiles`.`userid` = `GameTracker`.`users`.`userid` WHERE  `GameTracker`.`users`.`email` =  '%s' AND  `password` =  '%s'",email,pass);
   if (mysql_query(conn, query)) {
      fprintf(stderr, "%s\n", mysql_error(conn));
	return;
   }
	res = mysql_store_result(conn);
	char *sendmsg;
	char namestr[256];
	int num_rows = mysql_num_rows(res);
	if(num_rows == 0) {
		formatSend(sd,true,0,"\\nr\\\\ndone\\");
		return;
	}
	int len = 1024;
	sendmsg = (char *)malloc(len);
	memset((void *)sendmsg,0,len);
	sprintf_s(sendmsg,len,"\\nr\\%d",num_rows);
	while ((row = mysql_fetch_row(res)) != NULL) {
		sprintf_s(namestr,sizeof(namestr),"\\nick\\%s",row[0]);
		strncat(sendmsg,namestr,strlen(namestr)%len);
		if(sendUnique) {
			sprintf_s(namestr,sizeof(namestr),"\\uniquenick\\%s",row[1]);
			strncat(sendmsg,namestr,strlen(namestr)%len);
		}
		if(strlen(sendmsg)>(len/2)) {
			len *= 2;
			sendmsg = (char *)realloc(sendmsg,len);			
		}
		
        }
	strcat(sendmsg,"\\ndone\\");
	formatSend(sd,true,0,"%s",sendmsg);
        mysql_free_result(res);
	free((void *)sendmsg);
}
Exemple #11
0
void searchUsers(int sd, char *buff) {
	int searchnum = 0;
	int sesskey = 0;
	char nick[GP_NICK_LEN],email[GP_EMAIL_LEN],firstname[GP_FIRSTNAME_LEN],lastname[GP_LASTNAME_LEN],icquin[GP_AIMNAME_LEN],skip[GP_AIMNAME_LEN],uniquenick[GP_NICK_LEN];
	char *hideemail = "[hidden]";
	char *trueemail;
	int len = 1024;
	char tbuff[512];
	char *query;
	bool emailsearch = false;
	int namespaceid = find_paramint("namespaceid",buff);
	memset(&icquin,0,sizeof(icquin));
	if(find_param("email", buff, email, sizeof(email))) {
		mysql_real_escape_string(conn,email,email,strlen(email));
		len += strlen(email);
		searchnum++;
		emailsearch = true;
	}
	if(find_param("uniquenick", buff, uniquenick, sizeof(uniquenick))) {
		mysql_real_escape_string(conn,uniquenick,uniquenick,strlen(uniquenick));
		len += strlen(uniquenick);
		searchnum++;
	}
	if(find_param("nick", buff, nick, sizeof(nick))) {
		mysql_real_escape_string(conn,nick,nick,strlen(nick));
		len += strlen(nick);
		searchnum++;
	}
	if(find_param("firstname", buff, firstname, sizeof(firstname))) {
		mysql_real_escape_string(conn,firstname,firstname,strlen(firstname));
		len += strlen(firstname);
		searchnum++;
	}
	if(find_param("lastname", buff, lastname, sizeof(lastname))) {
		mysql_real_escape_string(conn,lastname,lastname,strlen(lastname));
		len += strlen(lastname);
		searchnum++;
	}
	if(find_param("icquin", buff, icquin, sizeof(icquin))) {
		mysql_real_escape_string(conn,icquin,icquin,strlen(icquin));
		len += strlen(icquin);
		searchnum++;
	}
	if(searchnum == 0) {
	       sendError(sd,"Error recieving request");
	       return;	
	}
	query = (char *)malloc(len);
	sprintf_s(query,len,"SELECT `profileid`,`nick`,`firstname`,`lastname`,`email`,`uniquenick`,`publicmask` FROM `GameTracker`.`profiles` INNER JOIN `GameTracker`.`users` ON `GameTracker`.`profiles`.`userid` = `GameTracker`.`users`.`userid` WHERE ");
	if(email[0] != 0) {
		sprintf_s(tbuff,sizeof(tbuff),"`email` = '%s'",email);
		if(--searchnum > 1) {
			strcat(tbuff, " AND ");
		}
		strcat(query,tbuff);
		if(strlen(query) > (len/2)) {
			len *= 2;
			query = (char *)realloc(query,len);
		}
	}
	if(nick[0] != 0) {
		sprintf_s(tbuff,sizeof(tbuff),"`nick` = '%s'",nick);
		if(--searchnum > 1) {
			strcat(tbuff, " AND ");
		}
		strcat(query,tbuff);
		if(strlen(query) > (len/2)) {
			len *= 2;
			query = (char *)realloc(query,len);
		}
	}
	if(firstname[0] != 0) {
		sprintf_s(tbuff,sizeof(tbuff),"`firstname` = '%s'",firstname);
		if(--searchnum > 1) {
			strcat(tbuff, " AND ");
		}
		strcat(query,tbuff);
		if(strlen(query) > (len/2)) {
			len *= 2;
			query = (char *)realloc(query,len);
		}
	}
	if(lastname[0] != 0) {
		sprintf_s(tbuff,sizeof(tbuff),"`lastname` = '%s'",lastname);
		if(--searchnum > 1) {
			strcat(tbuff, " AND ");
		}
		strcat(query,tbuff);
		if(strlen(query) > (len/2)) {
			len *= 2;
			query = (char *)realloc(query,len);
		}
	}
	if(uniquenick[0] != 0) {
		sprintf_s(tbuff,sizeof(tbuff),"`uniquenick` = '%s'",uniquenick);
		if(--searchnum > 1) {
			strcat(tbuff, " AND ");
		}
		strcat(query,tbuff);
		if(strlen(query) > (len/2)) {
			len *= 2;
			query = (char *)realloc(query,len);
		}
	}
	if(icquin[0] != 0) {
		sprintf_s(tbuff,sizeof(tbuff),"`icquin` = '%d'",atoi(icquin));
		strcat(query,tbuff);
	}
//	strcat(query," LIMIT 0,10");
	if (mysql_query(conn, query)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		return;
	}
	res = mysql_store_result(conn);
	int u_pid,u_hideemail;
	memset(query,0,len);
	while ((row = mysql_fetch_row(res)) != NULL) {
		u_pid = atoi(row[0]);
		sprintf_s(nick,sizeof(nick),"%s",row[1]);
		sprintf_s(firstname,sizeof(firstname),"%s",row[2]);
		sprintf_s(lastname,sizeof(lastname),"%s",row[3]);
		sprintf_s(email,sizeof(email),"%s",row[4]);
		if(row[5] != NULL) {
			sprintf_s(uniquenick,sizeof(uniquenick),"%s",row[5]);
		} else uniquenick[0] = 0;
		u_hideemail = ~atoi(row[6])&GP_MASK_EMAIL;
		if(u_hideemail != 0 && !emailsearch) {
			sprintf_s(email,sizeof(email),"[hidden]");
		}
		sprintf_s(tbuff,sizeof(tbuff),"\\bsr\\%d\\nick\\%s\\firstname\\%s\\lastname\\%s\\email\\%s\\uniquenick\\%s\\namespaceid\\%d",u_pid,nick,firstname,lastname,email,uniquenick,namespaceid);
		if(strlen(tbuff) > (len/2)) {
			len *= 2;
			query = (char *)realloc(query,len);			
		}
		strcat(query,tbuff);
   	}
	strcat(query,"\\bsrdone\\");
	formatSend(sd,true,0,"%s",query);
	end:
	mysql_free_result(res);
	free((void *)query);
}
static int gt_rdb_stmt_mysql_exec(GtRDBStmt *st, GtError *err)
{
  GtRDBStmtMySQL *stm;
  int rval, had_err = 0, num_fields;
  MYSQL_RES *meta_res = NULL;
  gt_assert(st);
  gt_error_check(err);
  stm = gt_rdb_stmt_mysql_cast(st);
  if (!stm->executed) {
    if (stm->num_params > 0) {
      gt_assert(stm->stmt && stm->params);
      if ((rval = mysql_stmt_bind_param(stm->stmt, stm->params))) {
        gt_error_set(err, GT_MYSQL_ERRMSG, rval, mysql_stmt_error(stm->stmt));
        had_err = -1;
      }
    }
    if (!had_err && (rval = mysql_stmt_execute(stm->stmt))) {
      gt_error_set(err, GT_MYSQL_ERRMSG, rval, mysql_stmt_error(stm->stmt));
      had_err = -1;
    }
    if (!had_err) {
      stm->executed = true;
      if (mysql_stmt_store_result(stm->stmt)) {
        gt_error_set(err, GT_MYSQL_ERRMSG,
                     had_err, mysql_stmt_error(stm->stmt));
        had_err = -1;
      }
      meta_res = mysql_stmt_result_metadata(stm->stmt);
      if (!had_err && meta_res) {
        int i = 0;
        /* statement returned a result */
        num_fields = mysql_num_fields(meta_res);
        stm->results = gt_calloc(num_fields, sizeof (MYSQL_BIND));
        /* prepare result buffers for each field */
        for (i=0;i<num_fields;i++) {
          MYSQL_FIELD *field;
          field = mysql_fetch_field(meta_res);
          stm->results[i].buffer_type = field->type;
          switch (field->type) {
            case MYSQL_TYPE_DOUBLE:
              {double *dbl = gt_calloc(1, sizeof (double));
              gt_hashtable_add(stm->buffers, &dbl);
              stm->results[i].buffer_length = sizeof (double);
              stm->results[i].buffer = dbl;}
              break;
            case MYSQL_TYPE_LONG:
            case MYSQL_TYPE_INT24:
            {int *l = gt_calloc(1, sizeof (int));
              gt_hashtable_add(stm->buffers, &l);
              stm->results[i].is_unsigned = false;
              stm->results[i].buffer_length = sizeof (int);
              stm->results[i].buffer = l;}
            case MYSQL_TYPE_SHORT:
            {short int *l = gt_calloc(1, sizeof (short int));
              gt_hashtable_add(stm->buffers, &l);
              stm->results[i].is_unsigned = false;
              stm->results[i].buffer_length = sizeof (short int);
              stm->results[i].buffer = l;}
            case MYSQL_TYPE_TINY:
              {signed char *l = gt_calloc(1, sizeof (signed char));
              gt_hashtable_add(stm->buffers, &l);
              stm->results[i].is_unsigned = false;
              stm->results[i].buffer_length = sizeof (signed char);
              stm->results[i].buffer = l;}
              break;
            case MYSQL_TYPE_STRING:
            case MYSQL_TYPE_VAR_STRING:
            case MYSQL_TYPE_BLOB:
            case MYSQL_TYPE_TINY_BLOB:
            case MYSQL_TYPE_MEDIUM_BLOB:
            case MYSQL_TYPE_LONG_BLOB:
            case MYSQL_TYPE_BIT:
              {char *str = gt_calloc(field->max_length+1, sizeof (char));
              gt_hashtable_add(stm->buffers, &str);
              GtUword *length = gt_calloc(1, sizeof (GtUword));
              gt_hashtable_add(stm->buffers, &length);
              stm->results[i].buffer = str;
              stm->results[i].buffer_length = field->max_length;
              stm->results[i].length = length;}
              break;
            default:
              /* unsupported data type */
              break;
          }
        }
        if (!had_err)
          mysql_stmt_bind_result(stm->stmt, stm->results);
        mysql_free_result(meta_res);
      } else {
        return 1;
      }
    }
  }
  if (!had_err) {
    switch ((rval = mysql_stmt_fetch(stm->stmt))) {
      case 0:
      default:
        break;
      case MYSQL_NO_DATA:
        had_err = 1;  /* last row read */
        break;
      case 1:
        gt_error_set(err, GT_MYSQL_ERRMSG, mysql_stmt_errno(stm->stmt),
                     mysql_stmt_error(stm->stmt));
        had_err = -1;
        break;
    }
  }
  return had_err;
}
Exemple #13
0
/* NOTE: Insure that mysql_conn->lock is NOT set on function entry */
static int _mysql_make_table_current(mysql_conn_t *mysql_conn, char *table_name,
				     storage_field_t *fields, char *ending)
{
	char *query = NULL;
	char *correct_query = NULL;
	MYSQL_RES *result = NULL;
	MYSQL_ROW row;
	int i = 0;
	List columns = NULL;
	ListIterator itr = NULL;
	char *col = NULL;
	int adding = 0;
	int run_update = 0;
	char *primary_key = NULL;
	char *unique_index = NULL;
	int old_primary = 0;
	char *old_index = NULL;
	char *temp = NULL, *temp2 = NULL;
	List keys_list = NULL;
	db_key_t *db_key = NULL;

	DEF_TIMERS;

	/* figure out the unique keys in the table */
	query = xstrdup_printf("show index from %s where non_unique=0",
			       table_name);
	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		return SLURM_ERROR;
	}
	xfree(query);
	while ((row = mysql_fetch_row(result))) {
		// row[2] is the key name
		if (!xstrcasecmp(row[2], "PRIMARY"))
			old_primary = 1;
		else if (!old_index)
			old_index = xstrdup(row[2]);
	}
	mysql_free_result(result);

	/* figure out the non-unique keys in the table */
	query = xstrdup_printf("show index from %s where non_unique=1",
			       table_name);
	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		return SLURM_ERROR;
	}
	xfree(query);

	itr = NULL;
	keys_list = list_create(_destroy_db_key);
	while ((row = mysql_fetch_row(result))) {
		if (!itr)
			itr = list_iterator_create(keys_list);
		else
			list_iterator_reset(itr);
		while ((db_key = list_next(itr))) {
			if (!xstrcmp(db_key->name, row[2]))
				break;
		}

		if (db_key) {
			xstrfmtcat(db_key->columns, ", %s", row[4]);
		} else {
			db_key = xmalloc(sizeof(db_key_t));
			db_key->name = xstrdup(row[2]); // name
			db_key->columns = xstrdup(row[4]); // column name
			list_append(keys_list, db_key); // don't use list_push
		}
	}
	mysql_free_result(result);

	if (itr) {
		list_iterator_destroy(itr);
		itr = NULL;
	}

	/* figure out the existing columns in the table */
	query = xstrdup_printf("show columns from %s", table_name);
	if (!(result = mysql_db_query_ret(mysql_conn, query, 0))) {
		xfree(query);
		xfree(old_index);
		FREE_NULL_LIST(keys_list);
		return SLURM_ERROR;
	}
	xfree(query);
	columns = list_create(slurm_destroy_char);
	while ((row = mysql_fetch_row(result))) {
		col = xstrdup(row[0]); //Field
		list_append(columns, col);
	}
	mysql_free_result(result);


	itr = list_iterator_create(columns);
#ifdef NO_ALTER_IGNORE_MYSQL
	/* In MySQL 5.7.4 we lost the ability to run 'alter ignore'.  This was
	 * needed when converting old tables to new schemas.  If people convert
	 * in the future from an older version of Slurm that needed the ignore
	 * to work they will have to downgrade mysql to <= 5.7.3 to make things
	 * work correctly or manually edit the database to get things to work.
	 */
	query = xstrdup_printf("alter table %s", table_name);
#else
	query = xstrdup_printf("alter ignore table %s", table_name);
#endif
	correct_query = xstrdup(query);
	START_TIMER;
	while (fields[i].name) {
		int found = 0;

		list_iterator_reset(itr);
		while ((col = list_next(itr))) {
			if (!xstrcmp(col, fields[i].name)) {
				xstrfmtcat(query, " modify `%s` %s,",
					   fields[i].name,
					   fields[i].options);
				xstrfmtcat(correct_query, " modify `%s` %s,",
					   fields[i].name,
					   fields[i].options);
				list_delete_item(itr);
				found = 1;
				break;
			}
		}
		if (!found) {
			if (i) {
				info("adding column %s after %s in table %s",
				     fields[i].name,
				     fields[i-1].name,
				     table_name);
				xstrfmtcat(query, " add `%s` %s after %s,",
					   fields[i].name,
					   fields[i].options,
					   fields[i-1].name);
				xstrfmtcat(correct_query, " modify `%s` %s,",
					   fields[i].name,
					   fields[i].options);
			} else {
				info("adding column %s at the beginning "
				     "of table %s",
				     fields[i].name,
				     table_name);
				xstrfmtcat(query, " add `%s` %s first,",
					   fields[i].name,
					   fields[i].options);
				xstrfmtcat(correct_query, " modify `%s` %s,",
					   fields[i].name,
					   fields[i].options);
			}
			adding = 1;
		}

		i++;
	}

	list_iterator_reset(itr);
	while ((col = list_next(itr))) {
		adding = 1;
		info("dropping column %s from table %s", col, table_name);
		xstrfmtcat(query, " drop %s,", col);
	}

	list_iterator_destroy(itr);
	FREE_NULL_LIST(columns);

	if ((temp = strstr(ending, "primary key ("))) {
		int open = 0, close =0;
		int end = 0;
		while (temp[end++]) {
			if (temp[end] == '(')
				open++;
			else if (temp[end] == ')')
				close++;
			else
				continue;
			if (open == close)
				break;
		}
		if (temp[end]) {
			end++;
			primary_key = xstrndup(temp, end);
			if (old_primary) {
				xstrcat(query, " drop primary key,");
				xstrcat(correct_query, " drop primary key,");
			}
			xstrfmtcat(query, " add %s,",  primary_key);
			xstrfmtcat(correct_query, " add %s,",  primary_key);

			xfree(primary_key);
		}
	}

	if ((temp = strstr(ending, "unique index ("))) {
		int open = 0, close =0;
		int end = 0;
		while (temp[end++]) {
			if (temp[end] == '(')
				open++;
			else if (temp[end] == ')')
				close++;
			else
				continue;
			if (open == close)
				break;
		}
		if (temp[end]) {
			end++;
			unique_index = xstrndup(temp, end);
			if (old_index) {
				xstrfmtcat(query, " drop index %s,",
					   old_index);
				xstrfmtcat(correct_query, " drop index %s,",
					   old_index);
			}
			xstrfmtcat(query, " add %s,", unique_index);
			xstrfmtcat(correct_query, " add %s,", unique_index);
			xfree(unique_index);
		}
	}
	xfree(old_index);

	temp2 = ending;
	itr = list_iterator_create(keys_list);
	while ((temp = strstr(temp2, ", key "))) {
		int open = 0, close = 0, name_end = 0;
		int end = 5;
		char *new_key_name = NULL, *new_key = NULL;
		while (temp[end++]) {
			if (!name_end && (temp[end] == ' ')) {
				name_end = end;
				continue;
			} else if (temp[end] == '(') {
				open++;
				if (!name_end)
					name_end = end;
			} else if (temp[end] == ')')
				close++;
			else
				continue;
			if (open == close)
				break;
		}
		if (temp[end]) {
			end++;
			new_key_name = xstrndup(temp+6, name_end-6);
			new_key = xstrndup(temp+2, end-2); // skip ', '
			while ((db_key = list_next(itr))) {
				if (!xstrcmp(db_key->name, new_key_name)) {
					list_remove(itr);
					break;
				}
			}
			list_iterator_reset(itr);
			if (db_key) {
				xstrfmtcat(query,
					   " drop key %s,", db_key->name);
				xstrfmtcat(correct_query,
					   " drop key %s,", db_key->name);
				_destroy_db_key(db_key);
			} else {
				xstrfmtcat(correct_query,
					   " drop key %s,", new_key_name);
				info("adding %s to table %s",
				     new_key, table_name);
			}

			xstrfmtcat(query, " add %s,",  new_key);
			xstrfmtcat(correct_query, " add %s,",  new_key);

			xfree(new_key);
			xfree(new_key_name);
		}
		temp2 = temp + end;
	}

	/* flush extra (old) keys */
	while ((db_key = list_next(itr))) {
		info("dropping key %s from table %s", db_key->name, table_name);
		xstrfmtcat(query, " drop key %s,", db_key->name);
	}
	list_iterator_destroy(itr);

	FREE_NULL_LIST(keys_list);

	query[strlen(query)-1] = ';';
	correct_query[strlen(correct_query)-1] = ';';
	//info("%d query\n%s", __LINE__, query);

	/* see if we have already done this definition */
	if (!adding) {
		char *quoted = slurm_add_slash_to_quotes(query);
		char *query2 = xstrdup_printf("select table_name from "
					      "%s where definition='%s'",
					      table_defs_table, quoted);
		MYSQL_RES *result = NULL;
		MYSQL_ROW row;

		xfree(quoted);
		run_update = 1;
		if ((result = mysql_db_query_ret(mysql_conn, query2, 0))) {
			if ((row = mysql_fetch_row(result)))
				run_update = 0;
			mysql_free_result(result);
		}
		xfree(query2);
		if (run_update) {
			run_update = 2;
			query2 = xstrdup_printf("select table_name from "
						"%s where table_name='%s'",
						table_defs_table, table_name);
			if ((result = mysql_db_query_ret(
				     mysql_conn, query2, 0))) {
				if ((row = mysql_fetch_row(result)))
					run_update = 1;
				mysql_free_result(result);
			}
			xfree(query2);
		}
	}

	/* if something has changed run the alter line */
	if (run_update || adding) {
		time_t now = time(NULL);
		char *query2 = NULL;
		char *quoted = NULL;

		if (run_update == 2)
			debug4("Table %s doesn't exist, adding", table_name);
		else
			debug("Table %s has changed.  Updating...", table_name);
		if (mysql_db_query(mysql_conn, query)) {
			xfree(query);
			return SLURM_ERROR;
		}
		quoted = slurm_add_slash_to_quotes(correct_query);
		query2 = xstrdup_printf("insert into %s (creation_time, "
					"mod_time, table_name, definition) "
					"values (%ld, %ld, '%s', '%s') "
					"on duplicate key update "
					"definition='%s', mod_time=%ld;",
					table_defs_table, now, now,
					table_name, quoted,
					quoted, now);
		xfree(quoted);
		if (mysql_db_query(mysql_conn, query2)) {
			xfree(query2);
			return SLURM_ERROR;
		}
		xfree(query2);
	}

	xfree(query);
	xfree(correct_query);
	query = xstrdup_printf("make table current %s", table_name);
	END_TIMER2(query);
	xfree(query);
	return SLURM_SUCCESS;
}
Exemple #14
0
bool MySQLStmtVariables::bind_result(MYSQL_STMT *stmt) {
  assert(m_arr.size() == mysql_stmt_field_count(stmt));

  MYSQL_RES *res = mysql_stmt_result_metadata(stmt);
  MYSQL_FIELD *fields = mysql_fetch_fields(res);
  for(int i = 0; i < m_arr.size(); i++) {
    MYSQL_BIND *b = &m_vars[i];
    b->is_unsigned = (fields[i].flags & UNSIGNED_FLAG) ? 1 : 0;

    switch (fields[i].type) {
      case MYSQL_TYPE_NULL:
        b->buffer_type = MYSQL_TYPE_NULL;
      case MYSQL_TYPE_DOUBLE:
      case MYSQL_TYPE_FLOAT:
        b->buffer_type = MYSQL_TYPE_DOUBLE;
        b->buffer_length = sizeof(double);
        break;
      case MYSQL_TYPE_LONGLONG:
#if MYSQL_VERSION_ID > 50002
      case MYSQL_TYPE_BIT:
#endif
      case MYSQL_TYPE_LONG:
      case MYSQL_TYPE_INT24:
      case MYSQL_TYPE_SHORT:
      case MYSQL_TYPE_YEAR:
      case MYSQL_TYPE_TINY:
        b->buffer_type = MYSQL_TYPE_LONGLONG;
        b->buffer_length = sizeof(int64_t);
        break;
      case MYSQL_TYPE_DATE:
      case MYSQL_TYPE_NEWDATE:
      case MYSQL_TYPE_DATETIME:
      case MYSQL_TYPE_TIMESTAMP:
      case MYSQL_TYPE_TIME:
      case MYSQL_TYPE_STRING:
      case MYSQL_TYPE_VARCHAR:
      case MYSQL_TYPE_VAR_STRING:
      case MYSQL_TYPE_ENUM:
      case MYSQL_TYPE_SET:
      case MYSQL_TYPE_LONG_BLOB:
      case MYSQL_TYPE_MEDIUM_BLOB:
      case MYSQL_TYPE_BLOB:
      case MYSQL_TYPE_TINY_BLOB:
      case MYSQL_TYPE_GEOMETRY:
      case MYSQL_TYPE_DECIMAL:
      case MYSQL_TYPE_NEWDECIMAL:
        b->buffer_type = MYSQL_TYPE_STRING;
        b->buffer_length = fields[i].max_length ?
                             fields[i].max_length :
                             fields[i].length;
        break;
      default:
        // There exists some more types in this enum like MYSQL_TYPE_TIMESTAMP2,
        // MYSQL_TYPE_DATETIME2, MYSQL_TYPE_TIME2 but they are just used on the
        // server
        assert(false);
    }

    if (b->buffer_length > 0) {
      b->buffer = calloc(1, b->buffer_length);
    }
  }
  mysql_free_result(res);

  return !mysql_stmt_bind_result(stmt, m_vars);
}
Exemple #15
0
void notifyNewContract(string userid, bool status = false)
{
	//mysql variables
	MYSQL mysql;
  MYSQL_RES *result;
  MYSQL_ROW row;
  string query;
  
	string to;
	string mobile;
	string targetid;
	string secret;
	string targetname;
	string message;
	
	//initiate mysql
	if(!mysql_init(&mysql))
  {
    cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
    return;
  }
  //cout << "MySQL initialized." << endl;
  
  //connect to database
  if(!mysql_real_connect(&mysql, MYSQLHOST, MYSQLUSER, MYSQLPASS, MYSQLDB, 0, NULL, 0))
  {
    cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
  	return;
  }
  //cout << "Connected to database." << endl;
	
	query = "SELECT * FROM users WHERE userid='" + userid + "'";
  if(mysql_query(&mysql, query.c_str()))
  {
		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
    return;
  }
  result = mysql_store_result(&mysql);
	if(row = mysql_fetch_row(result))
	{
		to = row[EMAIL];
		mobile = row[MOBILE];
		targetid = row[TARGETID];
		secret = row[SECRET];
	}
	mysql_free_result(result);
	
	//get name of target id
	int target = atoi(targetid.c_str());
	cout << "target: " << target << endl;
	if(target >= 0)
	{
		//you have a target
		query = "SELECT * FROM users WHERE userid='" + targetid + "'";
    if(mysql_query(&mysql, query.c_str()))
    {
  		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
      return;
    }
	  result = mysql_store_result(&mysql);
		if(row = mysql_fetch_row(result))
		{
			targetname = row[FIRST_NAME];
			targetname.append(" ");
			targetname.append(row[LAST_NAME]);
		}
		mysql_free_result(result);
		
		if(status)
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Current Status\r\n\r\nYour target's name is " + targetname + ". Your secret: " + secret + ".";
		else
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Your Next Contract\r\n\r\nYou have been assigned a new contract. Your target's name is " + targetname + ". Your secret: " + secret + ".";
	}
	else if(target == -1)
	{
		//you're dead
		if(status)
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Current Status\r\n\r\nAnother assassin has reported your death. Good luck next time.";
		else
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Reported Death\r\n\r\nAnother assassin has reported your death. Good luck next time.";
	}
	else if(target == -2)
	{
		//you dont have a target
		if(status)
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Current Status\r\n\r\nThe overlord hasn't found a suitable contract for you yet. Please wait while an assignment is made.";
		else
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Your Next Contract\r\n\r\nThe overlord hasn't found a suitable contract for you yet. Please wait while an assignment is made.";
	}
	else if(target == -3)
	{
		//you won the tournament
		if(status)
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Current Status\r\n\r\nCongratulations assassin, you have won the tournament. Everyone but you is dead.";
		else
			message = "From: Assassins Overlord <*****@*****.**>\r\nSubject: Good Work Assassin\r\n\r\nCongratulations assassin, you have won the tournament. Everyone but you is dead.";
	}
	
	//send email notifying of target
	if(!status) //send to email only if cell phone is looking for current status
	{
		mail(to, message);
		cout << "Email sent." << endl;
	}
	
	if(mobile.length() > 10)
	{
		mail(mobile, message);
		cout << "Text sent." << endl;
	}
}
Exemple #16
0
int SQL_getSolutionSource(JUDGE_SUBMISSION_ST *pstJudgeSubmission)
{
	if (NULL == pstJudgeSubmission)
	{
		write_log(JUDGE_ERROR,"SQL_getSolutionSourceEx, Input param is null...");
		return OS_ERR;
	}

	SQL_SemP();

	sprintf(query,"select source from solution_source where solution_id=%d",
			pstJudgeSubmission->stSolution.solutionId);

	int ret=mysql_real_query(mysql,query,(unsigned int)strlen(query));
	if(ret)
	{
		write_log(JUDGE_ERROR,mysql_error(mysql));
		SQL_SemV();
		return OS_ERR;
	}

	MYSQL_RES *recordSet = mysql_store_result(mysql);
	if (recordSet==NULL)
	{
		write_log(JUDGE_ERROR,"SQL_getSolutionSource");
		SQL_SemV();
		return OS_ERR;
	}

	FILE *fp_source = fopen(pstJudgeSubmission->sourcePath, "w");
	char code[MAX_CODE]={0};
	MYSQL_ROW row;

	if(row = mysql_fetch_row(recordSet))
	{
		sprintf(code, "%s", row[0]);
	}
	else
	{
		write_log(JUDGE_ERROR,"SQL_getSolutionSource Error");
	}

	if(pstJudgeSubmission->isTranscoding == 1)
	{
		int ii=0;
		/* 解决VS下字符问题 */
		while (code[ii]!='\0')
		{
			if (code[ii]=='\r')
			{
				code[ii] = '\n';
			}

			ii++;
		}
	}

	fprintf(fp_source, "%s", code);

	/* add for vjudge*/
	strcpy(pstJudgeSubmission->szSource, code);

	mysql_free_result(recordSet);
	fclose(fp_source);

	SQL_SemV();

	return OS_OK;
}
Exemple #17
0
//---------------------------------------------------------------------------
void __fastcall TFormDLLProgr::ComboBoxDiscipChange(TObject *Sender)
{
  indexDiscipForEditOneGroup=ComboBoxDiscip->ItemIndex;

  ListBoxOcenk->Clear();
  listIDsOfOcenk->Clear();

  ListBoxOcenk->Items->Add("Сем. по плану          Сем. по графику                 Оценка                      Балл");
  listIDsOfOcenk->Add("");
  ListBoxOcenk->Items->Add("");
  listIDsOfOcenk->Add("");

  if (ComboBoxDiscip->Items->Count==0)
  {
      BtnCheckOcenk->Enabled=false;
      return;
  }
  else BtnCheckOcenk->Enabled=true;
  int indexsel=ComboBoxDiscip->ItemIndex;
  if (indexsel < 0 || indexsel >= listIDsOfDiscip->Count) return;

  AnsiString idselDiscip=listIDsOfDiscip->Strings[indexsel];
  int classDiscip=listClassOfDiscip->Strings[indexsel].ToInt();

  MYSQL_RES *result;
  MYSQL_ROW row;

  AnsiString numplansem,numgraphsem,est,ball;
  int estindex;

  AnsiString SpaceStr;
  AnsiString Str;
  AnsiString myquery;
  myquery="SELECT id,numplansemestr,numgraphsemestr,estimation,ball FROM "+opts.DBProgress+" WHERE idstud="+ToStr(AnsiString(idstud))+" AND iddiscip="+ToStr(idselDiscip)+" AND deleted=0 ORDER BY numplansemestr";
  mysql_query(mysql,myquery.c_str());
  if (mysql_field_count(mysql))
  {
    result=mysql_store_result(mysql);
    if (result && mysql_num_rows(result))
    {
      while (row = mysql_fetch_row(result))
      {
        listIDsOfOcenk->Add(AnsiString(row[0]));
        numplansem=AnsiString(row[1]);
        numgraphsem=AnsiString(row[2]);
        estindex=AnsiString(row[3]).ToInt();
        est=arrOcenk[estindex];
        ball=GetStrWithReplacedPoints(AnsiString(row[4]),",");

        SpaceStr="      ";
        if (numplansem.Length()==1) SpaceStr+=" ";
        Str=SpaceStr+numplansem;
        SpaceStr="                                 ";
        if (numgraphsem.Length()==1) SpaceStr+=" ";
        Str+=SpaceStr+numgraphsem;
        SpaceStr="                       ";
        switch(estindex)
        {
         case 0: SpaceStr+="           ";break;
         case 1: SpaceStr+="           ";break;
         case 2: SpaceStr+="  ";break;
         case 4: SpaceStr+="           ";break;
         case 5: SpaceStr+="          ";break;
        }
        Str+=SpaceStr+est;
        switch(estindex)
        {
         case 0: SpaceStr="              ";break;
         case 1: SpaceStr="               ";break;
         case 2: SpaceStr="   ";break;
         case 3: SpaceStr=" ";break;
         case 4: SpaceStr="              ";break;
         case 5: SpaceStr="           ";break;
        }
        SpaceStr+="        ";
        Str+=SpaceStr+ball;
        SpaceStr="                 ";
        if (IS_PERIOD(classDiscip))
          Str+=SpaceStr;
        ListBoxOcenk->Items->Add(Str);
      }
    }
    mysql_free_result(result);
  }

  ListBoxOcenkClick(ListBoxOcenk);
}
	/**
		将数据更新到表中
	*/
	static bool writeDB(DB_TABLE_OP optype, DBInterface* dbi, DB_OP_TABLE_ITEM_DATA_BOX& opTableItemDataBox)
	{
		bool ret = true;

		if(!opTableItemDataBox.isEmpty)
		{
			SqlStatement* pSqlcmd = createSql(dbi, optype, opTableItemDataBox.tableName, 
				opTableItemDataBox.parentTableDBID, 
				opTableItemDataBox.dbid, opTableItemDataBox.items);

			ret = pSqlcmd->query();
			opTableItemDataBox.dbid = pSqlcmd->dbid();
			delete pSqlcmd;
		}

		if(optype == TABLE_OP_INSERT)
		{
			// 开始更新所有的子表
			DB_OP_TABLE_DATAS::iterator iter1 = opTableItemDataBox.optable.begin();
			for(; iter1 != opTableItemDataBox.optable.end(); iter1++)
			{
				DB_OP_TABLE_ITEM_DATA_BOX& wbox = *iter1->second.get();
				
				// 绑定表关系
				wbox.parentTableDBID = opTableItemDataBox.dbid;

				// 更新子表
				writeDB(optype, dbi, wbox);
			}
		}
		else
		{
			// 如果有父ID首先得到该属性数据库中同父id的数据有多少条目, 并取出每条数据的id
			// 然后将内存中的数据顺序更新至数据库, 如果数据库中有存在的条目则顺序覆盖更新已有的条目, 如果数据数量
			// 大于数据库中已有的条目则插入剩余的数据, 如果数据少于数据库中的条目则删除数据库中的条目
			// select id from tbl_SpawnPoint_xxx_values where parentID = 7;
			KBEUnordered_map< std::string, std::vector<DBID> > childTableDBIDs;

			if(opTableItemDataBox.dbid > 0)
			{
				DB_OP_TABLE_DATAS::iterator iter1 = opTableItemDataBox.optable.begin();
				for(; iter1 != opTableItemDataBox.optable.end(); iter1++)
				{
					DB_OP_TABLE_ITEM_DATA_BOX& wbox = *iter1->second.get();

					KBEUnordered_map<std::string, std::vector<DBID> >::iterator iter = 
						childTableDBIDs.find(opTableItemDataBox.tableName);

					if(iter == childTableDBIDs.end())
					{
						std::vector<DBID> v;
						childTableDBIDs.insert(std::pair< std::string, std::vector<DBID> >(wbox.tableName, v));
					}
				}
				
				if(childTableDBIDs.size() > 1)
				{
					std::string sqlstr_getids;
					KBEUnordered_map< std::string, std::vector<DBID> >::iterator tabiter = childTableDBIDs.begin();
					for(; tabiter != childTableDBIDs.end();)
					{
						char sqlstr[MAX_BUF * 10];
						kbe_snprintf(sqlstr, MAX_BUF * 10, "select count(id) from "ENTITY_TABLE_PERFIX"_%s where "TABLE_PARENTID_CONST_STR"=%"PRDBID" union all ", 
							tabiter->first.c_str(),
							opTableItemDataBox.dbid);
						
						sqlstr_getids += sqlstr;

						kbe_snprintf(sqlstr, MAX_BUF * 10, "select id from "ENTITY_TABLE_PERFIX"_%s where "TABLE_PARENTID_CONST_STR"=%"PRDBID, 
							tabiter->first.c_str(),
							opTableItemDataBox.dbid);

						sqlstr_getids += sqlstr;
						if(++tabiter != childTableDBIDs.end())
							sqlstr_getids += " union all ";
					}
					
					if(dbi->query(sqlstr_getids.c_str(), sqlstr_getids.size(), false))
					{
						MYSQL_RES * pResult = mysql_store_result(static_cast<DBInterfaceMysql*>(dbi)->mysql());
						if(pResult)
						{
							MYSQL_ROW arow;
							int32 count = 0;
							tabiter = childTableDBIDs.begin();
							bool first = true;

							while((arow = mysql_fetch_row(pResult)) != NULL)
							{
								if(count == 0)
								{
									StringConv::str2value(count, arow[0]);
									if(!first || count <= 0)
										tabiter++;
									continue;
								}

								DBID old_dbid;
								StringConv::str2value(old_dbid, arow[0]);
								tabiter->second.push_back(old_dbid);
								count--;
								first = false;
							}

							mysql_free_result(pResult);
						}
					}
				}
				else if(childTableDBIDs.size() == 1)
				{
					KBEUnordered_map< std::string, std::vector<DBID> >::iterator tabiter = childTableDBIDs.begin();
						char sqlstr[MAX_BUF * 10];
						kbe_snprintf(sqlstr, MAX_BUF * 10, "select id from "ENTITY_TABLE_PERFIX"_%s where "TABLE_PARENTID_CONST_STR"=%"PRDBID, 
							tabiter->first.c_str(),
							opTableItemDataBox.dbid);

						if(dbi->query(sqlstr, strlen(sqlstr), false))
						{
							MYSQL_RES * pResult = mysql_store_result(static_cast<DBInterfaceMysql*>(dbi)->mysql());
							if(pResult)
							{
								MYSQL_ROW arow;
								while((arow = mysql_fetch_row(pResult)) != NULL)
								{
									DBID old_dbid;
									StringConv::str2value(old_dbid, arow[0]);
									tabiter->second.push_back(old_dbid);
								}

								mysql_free_result(pResult);
							}
						}
				}
			}

			// 如果是要清空此表, 则循环N次已经找到的dbid, 使其子表中的子表也能有效删除
			if(!opTableItemDataBox.isEmpty)
			{
				// 开始更新所有的子表
				DB_OP_TABLE_DATAS::iterator iter1 = opTableItemDataBox.optable.begin();
				for(; iter1 != opTableItemDataBox.optable.end(); iter1++)
				{
					DB_OP_TABLE_ITEM_DATA_BOX& wbox = *iter1->second.get();
					
					if(wbox.isEmpty)
						continue;

					// 绑定表关系
					wbox.parentTableDBID = opTableItemDataBox.dbid;

					KBEUnordered_map<std::string, std::vector<DBID> >::iterator iter = 
						childTableDBIDs.find(wbox.tableName);
					
					if(iter != childTableDBIDs.end())
					{
						if(iter->second.size() > 0)
						{
							wbox.dbid = iter->second.front();
							iter->second.erase(iter->second.begin());
						}

						if(iter->second.size() <= 0)
						{
							childTableDBIDs.erase(wbox.tableName);
						}
					}

					// 更新子表
					writeDB(optype, dbi, wbox);
				}
			}
			
			// 删除废弃的数据项
			KBEUnordered_map< std::string, std::vector<DBID> >::iterator tabiter = childTableDBIDs.begin();
			for(; tabiter != childTableDBIDs.end(); tabiter++)
			{
				if(tabiter->second.size() == 0)
					continue;

				// 先删除数据库中的记录
				std::string sqlstr = "delete from "ENTITY_TABLE_PERFIX"_";
				sqlstr += tabiter->first;
				sqlstr += " where "TABLE_ID_CONST_STR" in (";

				std::vector<DBID>::iterator iter = tabiter->second.begin();
				for(; iter != tabiter->second.end(); iter++)
				{
					DBID dbid = (*iter);

					char sqlstr1[MAX_BUF];
					kbe_snprintf(sqlstr1, MAX_BUF, "%"PRDBID, dbid);
					sqlstr += sqlstr1;
					sqlstr += ",";
				}
				
				sqlstr.erase(sqlstr.size() - 1);
				sqlstr += ")";
				bool ret = dbi->query(sqlstr.c_str(), sqlstr.size(), false);
				KBE_ASSERT(ret);

				DB_OP_TABLE_DATAS::iterator iter1 = opTableItemDataBox.optable.begin();
				for(; iter1 != opTableItemDataBox.optable.end(); iter1++)
				{
					DB_OP_TABLE_ITEM_DATA_BOX& wbox = *iter1->second.get();
					if(wbox.tableName == tabiter->first)
					{
						std::vector<DBID>::iterator iter = tabiter->second.begin();
						for(; iter != tabiter->second.end(); iter++)
						{
							DBID dbid = (*iter);
							
							wbox.parentTableDBID = opTableItemDataBox.dbid;
							wbox.dbid = dbid;
							wbox.isEmpty = true;

							// 更新子表
							writeDB(optype, dbi, wbox);
						}
					}
				}
			}
		}
		return ret;
	}
bool SharedMemory::LoadItems(){
	char errbuf[MYSQL_ERRMSG_SIZE];
	char *query = 0;
	MYSQL_RES *result;
	MYSQL_ROW row;
	int id;
	query = new char[256];
	strcpy(query, "SELECT MAX(id) FROM items");

	EQC::Common::PrintF(CP_SHAREDMEMORY, "Loading items... ");
	if (Database::Instance()->RunQuery(query, strlen(query), errbuf, &result)) {
		safe_delete(query);
		row = mysql_fetch_row(result);
		if (row != 0 && row[0] > 0)
		{ 
			getPtr()->max_item = atoi(row[0]);
			if (getPtr()->max_item >= MAXITEMID) {
				EQC::Common::PrintF(CP_SHAREDMEMORY, "bool SharedMemory::LoadItems(): More items than MAXITEMID. Change constant in SharedMemory.hpp");
				return false;
			}
			memset(&getPtr()->item_array, 0, sizeof(getPtr()->item_array));
			mysql_free_result(result);

			MakeAnyLenString(&query, "SELECT id,raw_data FROM items");

			if (Database::Instance()->RunQuery(query, strlen(query), errbuf, &result))
			{
				safe_delete_array(query);//delete[] query;
				while(row = mysql_fetch_row(result))
				{
					unsigned long* lengths;
					lengths = mysql_fetch_lengths(result);
					if (lengths[1] == sizeof(Item_Struct))
					{
						id = atoi(row[0]);
						memcpy(&getPtr()->item_array[id], row[1], sizeof(Item_Struct));
						//Yeahlight: Client item exceptions
						if(getPtr()->item_array[id].type == 0)
						{
							//Yeahlight: Remove 'BST' (01000000 00000000) from item classes as long as the list does not compute to 'ALL' (01111111 11111111)
							if(getPtr()->item_array[id].common.classes - 16384 >= 0 && getPtr()->item_array[id].common.classes != 32767)
								getPtr()->item_array[id].common.classes -= 16384;
							//Yeahlight: Remove 'VAH' (00100000 00000000) from item races as long as the list does not compute to 'ALL' (00111111 11111111)
							if(getPtr()->item_array[id].common.normal.races - 8192 >= 0 && getPtr()->item_array[id].common.normal.races != 16383)
								getPtr()->item_array[id].common.normal.races -= 8192;
							//Yeahlight: Our client cannot handle H2H skill weapons, so flag them as 1HB
							if(getPtr()->item_array[id].common.itemType == ItemTypeHand2Hand)
								getPtr()->item_array[id].common.itemType = ItemType1HB;
							//Yeahlight: There will be no gear with recommended levels on the server, so zero out this field
							if(getPtr()->item_array[id].common.recommendedLevel != 0)
								getPtr()->item_array[id].common.recommendedLevel = 0;
							//Yeahlight: This purges focus effects from our items
							if(getPtr()->item_array[id].common.click_effect_id >= 2330 && getPtr()->item_array[id].common.click_effect_id <= 2374)
							{
								getPtr()->item_array[id].common.click_effect_id = 0;
								getPtr()->item_array[id].common.spell_effect_id = 0;
								getPtr()->item_array[id].common.charges = 0;
								getPtr()->item_array[id].common.normal.click_effect_type = 0;
								getPtr()->item_array[id].common.effecttype = 0;
								getPtr()->item_array[id].common.clicktype = 0;
							}
						}
						//Yeahlight: Client container exceptions
						else if(getPtr()->item_array[id].type == 1)
						{
							//Tazadar : We clean this or the client crashes or bag are full of shit
							memset(&getPtr()->item_array[id].common.level,0x00,69*sizeof(int8));
							memset(&getPtr()->item_array[id].unknown0144[0],0x00,68*sizeof(int8));
						}
						//Yeahlight: Client book exceptions
						else if(getPtr()->item_array[id].type == 2)
						{

						}
					}
					else
					{
						cout << "Invalid items in database..." << endl;
					}
					Sleep(0);
				}
				mysql_free_result(result);
			}
			else {
				cerr << "Error in PopulateZoneLists query '" << query << "' " << errbuf << endl;
				safe_delete_array(query);//delete[] query;
				return false;
			}
		}
		else {
			mysql_free_result(result);
		}
	}
	else {
		cerr << "Error in PopulateZoneLists query '" << query << "' " << errbuf << endl;
		safe_delete_array(query);//delete[] query;
		return false;
	}
	EQC::Common::PrintF(CP_SHAREDMEMORY, "Item loading finished.");
	return true;
}
Exemple #20
0
static void free_result( value o ) {
	result *r = RESULT(o);
	mysql_free_result(r->r);
}
Exemple #21
0
void ModifyBook()   /*修改图书信息*/
{
    char id[10];   /*结果集中的行数*/
    char *sql;    
    char dest[500] ={"  "};
    char dest1[500] ={"  "};
    
    char *bookname;
    char *author;
    char *bookconcern;
    
    if (!mysql_real_connect(&mysql,"127.0.0.1","root","111","db_books",0,NULL,0))
    {
        printf("\t 不能连接数据库!\n");
    }
    else
    {
        /*数据库连接成功*/
        // printf("连接成功");
        printf("\t 请输入您想要修改的图书编号.");
        
        scanf("%s",id);   /*输入图书编号*/
        sql = "select * from tb_book where id=";
        strcat(dest,sql);
        strcat(dest,id);    /*将图书编号追加到sql语句后面*/
        
        //printf("%s\n",dest);
        
        /*查询该图书信息是否存在*/
        if(mysql_query(&mysql,dest))
        {   //如果查询失败
            printf("\n  查询 tb_book 数据表失败! \n");
        }
        else
        {
            result=mysql_store_result(&mysql); //获得结果集
            if(mysql_num_rows(result)!=NULL)
            {
                //有记录的情况,只有有记录取数据才有意义
                printf("\t 发现记录信息,是否显示?(y/n) ");
                scanf("%s",ch);
                if(strcmp(ch,"Y")==0||strcmp(ch,"y")==0)/*判断是否要显示查找到的信息*/
                {
                    printf("\t ════════════════════════════ \n");
                    printf("\t               ***** 显示图书信息 *****                   \n");
                    printf("\t ════════════════════════════ \n");
                    printf("\t图书编号       图书名         作者        出版社      \n");
                    printf("\t -------------------------------------------------------- \n");
                    while((row=mysql_fetch_row(result)))
                    {   //取出结果集中记录
                        fprintf(stdout,"\t   %s             %s             %s          %s   \n",row[0],row[1],row[2],row[3]);  //输出这行记录
                    }
                    printf("\t ════════════════════════════ \n");
                }
                
                
                printf("\t Modify?(y/n)");
                scanf("%s",ch);
                if (strcmp(ch,"Y")==0||strcmp(ch,"y")==0)    /*判断是否需要录入*/
                {

 
                    sql = "update tb_book set bookname= '";
                    strcat(dest1,sql);
                    //   printf("%s",sql);
                    bookname = (char*)malloc(20);
                    author = (char*)malloc(20);
                    bookconcern = (char*)malloc(20);

                    printf("\t 图书名:");
                    scanf("%s",bookname);   /*输入图书名*/
                    
                    strcat(dest1,bookname); 
                    //  printf("%s",&bookname);

                    printf("\t 作者:");
                    scanf("%s",author);    /*输入作者*/
                    strcat(dest1,"', author= '");
                    strcat(dest1,author);    /*追加sql语句*/                        
                    
                    printf("\t 出版社:");
                    scanf("%s",bookconcern);    /*输入出版社*/
                    strcat(dest1,"', bookconcern = '");
                    strcat(dest1,bookconcern);    /*追加sql语句*/
                    
                    strcat(dest1,"' where id= ");
                    strcat(dest1,id);                        
                    
                    //printf("%s",dest1);

                    if(mysql_query(&mysql,dest1)!=0)
                    {   
                        fprintf(stderr,"\t 不能修改记录!\n",mysql_error(&mysql));                            
                    }
                    else
                    {
                        printf("\t 修改成功!\n");
                    }
                }
                
            }
            else
            {
                printf("\t 没有发现要修改的信息!\n");
            }
        }
        mysql_free_result(result);          //释放结果集
    }
    mysql_close(&mysql);     //释放连接
    inquire();   /*询问是否显示主菜单*/
}
Exemple #22
0
void db_free(MYSQL_RES **pstRst)
{
	mysql_free_result(*pstRst);
}
Exemple #23
0
int
cmyth_mysql_get_prog_finder_time(cmyth_database_t db, cmyth_program_t **prog,  time_t starttime, char *program_name) 
{
	MYSQL_RES *res=NULL;
	MYSQL_ROW row;
        char query[630];
	char *N_title;
	int rows=0;
	int n = 50;
	int ch;


	if(cmyth_db_check_connection(db) != 0)
	{
               cmyth_dbg(CMYTH_DBG_ERROR, "%s: cmyth_db_check_connection failed\n",
                           __FUNCTION__);
               fprintf(stderr,"%s: cmyth_db_check_connection failed\n", __FUNCTION__);
	       return -1;
	}

	N_title = ref_alloc(strlen(program_name)*2+1);
	mysql_real_escape_string(db->mysql,N_title,program_name,strlen(program_name)); 

        //sprintf(query, "SELECT chanid,starttime,endtime,title,description,subtitle,programid,seriesid,category FROM program WHERE starttime >= '%s' and title ='%s' ORDER BY `starttime` ASC ", starttime, N_title);
        snprintf(query, 630, "SELECT program.chanid,UNIX_TIMESTAMP(program.starttime),UNIX_TIMESTAMP(program.endtime),program.title,program.description,program.subtitle,program.programid,program.seriesid,program.category, channel.channum, channel.callsign, channel.name, channel.sourceid FROM program LEFT JOIN channel on program.chanid=channel.chanid WHERE starttime >= FROM_UNIXTIME(%d) and title ='%s' ORDER BY `starttime` ASC ", (int)starttime, N_title);
	ref_release(N_title);
	fprintf(stderr, "%s\n", query);
        cmyth_dbg(CMYTH_DBG_ERROR, "%s: query= %s\n", __FUNCTION__, query);
        if(mysql_query(db->mysql,query)) {
                 cmyth_dbg(CMYTH_DBG_ERROR, "%s: mysql_query() Failed: %s\n", 
                           __FUNCTION__, mysql_error(db->mysql));
		return -1;
       	}
	cmyth_dbg(CMYTH_DBG_ERROR, "n =  %d\n",n);
        res = mysql_store_result(db->mysql);
	cmyth_dbg(CMYTH_DBG_ERROR, "n =  %d\n",n);
	while((row = mysql_fetch_row(res))) {
			cmyth_dbg(CMYTH_DBG_ERROR, "n =  %d\n",n);
        	if (rows == n) {
                	n++;
			cmyth_dbg(CMYTH_DBG_ERROR, "realloc n =  %d\n",n);
                       	*prog=realloc(*prog,sizeof(**prog)*(n));
               	}
			cmyth_dbg(CMYTH_DBG_ERROR, "rows =  %d\nrow[0]=%d\n",rows, row[0]);
			cmyth_dbg(CMYTH_DBG_ERROR, "row[1]=%d\n",row[1]);
			ch = atoi(row[0]);
			(*prog)[rows].chanid=ch;
			cmyth_dbg(CMYTH_DBG_ERROR, "prog[%d].chanid =  %d\n",rows, (*prog)[rows].chanid);
			(*prog)[rows].recording=0;
			(*prog)[rows].starttime = atoi(row[1]);
			(*prog)[rows].endtime = atoi(row[2]);
			sizeof_strncpy ((*prog)[rows].title, row[3]);
			sizeof_strncpy ((*prog)[rows].description, row[4]);
			sizeof_strncpy ((*prog)[rows].subtitle, row[5]);
			sizeof_strncpy ((*prog)[rows].programid, row[6]);
			sizeof_strncpy ((*prog)[rows].seriesid, row[7]);
			sizeof_strncpy ((*prog)[rows].category, row[8]);
			(*prog)[rows].channum = atoi (row[9]);
			sizeof_strncpy ((*prog)[rows].callsign,row[10]);
			sizeof_strncpy ((*prog)[rows].name,row[11]);
			(*prog)[rows].sourceid = atoi (row[12]);
        		cmyth_dbg(CMYTH_DBG_ERROR, "prog[%d].chanid =  %d\n",rows, (*prog)[rows].chanid);
        		cmyth_dbg(CMYTH_DBG_ERROR, "prog[%d].title =  %s\n",rows, (*prog)[rows].title);
			rows++;
        }
        mysql_free_result(res);
        cmyth_dbg(CMYTH_DBG_ERROR, "%s: rows= %d\n", __FUNCTION__, rows);
	return rows;
}
Exemple #24
0
ERRCODE CPOSDB::GetPOS(LPTSTR lpMAC, POS* pPOS)
{
	if (pPOS == NULL)
	{
		return err_InvalidParameter;
	}
	ERRCODE errRet = err_OK;
	if (m_database.Connect() != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Open;
	}

	if (m_database.ProcedureInit(PROCEDURE_POS_SELECT) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}
	if (m_database.ProcedureAddParam("MAC", adVarChar, adParamInput, lpMAC) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}

	if (m_database.ProcedureExecute() != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}

	MYSQL_RES *pResults = m_database.ProcedureGetResult();
	if (pResults== NULL)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}

	MYSQL_ROW row;
	int iItem = 0;
	if((row = mysql_fetch_row(pResults)))   
	{ 
		int iFieldNum = mysql_num_fields(pResults);
		if (iFieldNum < 3)
		{
			g_log.Write(_T("POSDB Error:Num fields not match!"));
			mysql_free_result(pResults);
			m_database.FreeOtherResults();
			return err_DB_NumFieldNotMatch;
		}

		iItem = 0;
		pPOS->csID = LPSTR(row[iItem++]); 
		pPOS->csPCID = LPSTR(row[iItem++]); 
		pPOS->csPCMAC = LPSTR(row[iItem++]); 
	} 
	else
	{
		errRet = err_POS_NotExist;
	}
	mysql_free_result(pResults);
	m_database.FreeOtherResults();

	return errRet;
}
Exemple #25
0
int
cmyth_mysql_get_commbreak_list(cmyth_database_t db, int chanid, char * start_ts_dt, cmyth_commbreaklist_t breaklist, int conn_version) 
{
	MYSQL_RES *res = NULL;
	MYSQL_ROW row;
	int resolution = 30;
	char * query_str;
	int rows = 0;
	cmyth_mysql_query_t * query;
	cmyth_commbreak_t commbreak = NULL;
	int i = 0;
	long long start_previous = 0;
	long long end_previous = 0;

	if (conn_version>=43) {
		query_str = "SELECT m.type,m.mark,s.mark,s.offset  FROM recordedmarkup m INNER JOIN recordedseek AS s ON m.chanid = s.chanid AND m.starttime = s.starttime  WHERE m.chanid = ? AND m.starttime = ? AND m.type in (?,?) and FLOOR(m.mark/?)=FLOOR(s.mark/?) ORDER BY `m`.`mark` LIMIT 300 ";
	}
	else { 
		query_str = "SELECT m.type AS type, m.mark AS mark, s.offset AS offset FROM recordedmarkup m INNER JOIN recordedseek AS s ON (m.chanid = s.chanid AND m.starttime = s.starttime AND (FLOOR(m.mark / 15) + 1) = s.mark) WHERE m.chanid = ? AND m.starttime = ? AND m.type IN (?, ?) ORDER BY mark;";
	}

	query = cmyth_mysql_query_create(db,query_str);
		
	cmyth_dbg(CMYTH_DBG_ERROR,"%s, query=%s\n", __FUNCTION__,query_str);

	if ( (conn_version>=43) && ( 
		cmyth_mysql_query_param_int(query, chanid) < 0
		|| cmyth_mysql_query_param_str(query, start_ts_dt) < 0
		|| cmyth_mysql_query_param_int(query, CMYTH_COMMBREAK_START) < 0
		|| cmyth_mysql_query_param_int(query, CMYTH_COMMBREAK_END) < 0
		|| cmyth_mysql_query_param_int(query, resolution ) < 0
		|| cmyth_mysql_query_param_int(query, resolution ) < 0
		) ) {
		cmyth_dbg(CMYTH_DBG_ERROR,"%s, binding of query parameters failed! Maybe we're out of memory?\n", __FUNCTION__);
		ref_release(query);
		return -1;
	}
		
	if ( (conn_version < 43) && (cmyth_mysql_query_param_int(query, chanid) < 0
		|| cmyth_mysql_query_param_str(query, start_ts_dt) < 0
		|| cmyth_mysql_query_param_int(query, CMYTH_COMMBREAK_START) < 0
		|| cmyth_mysql_query_param_int(query, CMYTH_COMMBREAK_END) < 0
		) ) {
		cmyth_dbg(CMYTH_DBG_ERROR,"%s, binding of query parameters failed! Maybe we're out of memory?\n", __FUNCTION__);
		ref_release(query);
		return -1;
	}
	res = cmyth_mysql_query_result(query);
	ref_release(query);
	if (res == NULL) {
		cmyth_dbg(CMYTH_DBG_ERROR, "%s, finalisation/execution of query failed!\n", __FUNCTION__);
		return -1;
	}

	if (conn_version >=43) {
		breaklist->commbreak_count = cmyth_mysql_query_commbreak_count(db,chanid,start_ts_dt);
	}
	else {
		breaklist->commbreak_count = mysql_num_rows(res) / 2;
	}
	breaklist->commbreak_list = malloc(breaklist->commbreak_count * sizeof(cmyth_commbreak_t));
	//cmyth_dbg(CMYTH_DBG_ERROR, "%s: %ld\n",__FUNCTION__,breaklist->commbreak_count);

	if (!breaklist->commbreak_list) {
		cmyth_dbg(CMYTH_DBG_ERROR, "%s: malloc() failed for list\n",
			__FUNCTION__);
		return -1;
	}
	memset(breaklist->commbreak_list, 0, breaklist->commbreak_count * sizeof(cmyth_commbreak_t));

	if (conn_version >=43) {
		while ((row = mysql_fetch_row(res))) {
			if (safe_atoi(row[0]) == CMYTH_COMMBREAK_START) {
				if ( safe_atoll(row[1]) != start_previous ) {
					commbreak = cmyth_commbreak_create();
					commbreak->start_mark = safe_atoll(row[1]);
					commbreak->start_offset = safe_atoll(row[3]);
					start_previous = commbreak->start_mark;
				}
				else if ( safe_atoll(row[1]) == safe_atoll(row[2]) ) { 
					commbreak = cmyth_commbreak_create();
					commbreak->start_mark = safe_atoll(row[1]);
					commbreak->start_offset = safe_atoll(row[3]);
				}
			} else if (safe_atoi(row[0]) == CMYTH_COMMBREAK_END) {
				if ( safe_atoll(row[1]) != end_previous ) {
					if (commbreak == NULL) {
						cmyth_dbg(CMYTH_DBG_ERROR,
							  "%s: error at %d\n",
							  __FUNCTION__,
							  __LINE__);
						return -1;
					}
					commbreak->end_mark = safe_atoll(row[1]);
					commbreak->end_offset = safe_atoll(row[3]);
					breaklist->commbreak_list[rows] = commbreak;
					end_previous = commbreak->end_mark;
					rows++;
				}
				else if ( safe_atoll(row[1]) == safe_atoll(row[2]) ) {
					if (commbreak == NULL) {
						cmyth_dbg(CMYTH_DBG_ERROR,
							  "%s: error at %d\n",
							  __FUNCTION__,
							  __LINE__);
						return -1;
					}
					commbreak->end_mark = safe_atoll(row[1]);
					commbreak->end_offset = safe_atoll(row[3]);
					breaklist->commbreak_list[rows] = commbreak;
					if (end_previous != safe_atoll(row[1]) ) {
						rows++;
					}
				}
			}
			else {
				cmyth_dbg(CMYTH_DBG_ERROR, "%s: Unknown COMMBREAK returned\n", 
					__FUNCTION__);
				return -1;
			}
			i++;
		}
	}

	// mythtv protolcol version < 43 
	else {
		while ((row = mysql_fetch_row(res))) {
			if ((i % 2) == 0) {
				if (safe_atoi(row[0]) != CMYTH_COMMBREAK_START) {
					return -1;
				}
				commbreak = cmyth_commbreak_create();
				commbreak->start_mark = safe_atoll(row[1]);
				commbreak->start_offset = safe_atoll(row[2]);
				i++;
			} else {
				if (safe_atoi(row[0]) != CMYTH_COMMBREAK_END) {
					return -1;
				}
				commbreak->end_mark = safe_atoll(row[1]);
				commbreak->end_offset = safe_atoll(row[2]);
				breaklist->commbreak_list[rows] = commbreak;
				i = 0;
				rows++;
			}
		}
	}
	mysql_free_result(res);
	cmyth_dbg(CMYTH_DBG_ERROR, "%s: COMMBREAK rows= %d\n", __FUNCTION__, rows);
	return rows;
}
Exemple #26
0
ERRCODE CPOSDB::GetPOSs(DWORD dwPageNum, 
											DWORD dwNumPerPage, 
											DWORD &dwTotalPage, 
											DWORD &dwTotalNum, 
											vector<POS*> &vctPOS)
{
	if (m_database.Connect() != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Open;
	}

	if (m_database.ProcedureInit(PROCEDURE_POS_GET) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}
	if (m_database.ProcedureAddParam("numPerPage", adInteger, adParamInput, &dwNumPerPage) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}
	if (m_database.ProcedureAddParam("pageNum", adInteger, adParamInput, &dwPageNum) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}
	if (m_database.ProcedureAddParam("totalNum", adInteger, adParamOutput) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}
	if (m_database.ProcedureAddParam("totalPage", adInteger, adParamOutput) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}

	if (m_database.ProcedureExecute() != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}

	MYSQL_RES *pResults = m_database.ProcedureGetResult();
	if (pResults== NULL)
	{
		g_log.Write(m_database.GetLastErrorMsg());
		return err_DB_Proc_Execute;
	}

	MYSQL_ROW row;
	int iItem = 0;;
	while((row = mysql_fetch_row(pResults)))   
	{ 
		int iFieldNum = mysql_num_fields(pResults);
		if (iFieldNum < 3)
		{
			g_log.Write(_T("POSDB Error:Num fields not match!"));
			for (unsigned int i = 0; i < vctPOS.size(); i++)
			{
				delete vctPOS[i];
				vctPOS[i] = NULL;
			}
			vctPOS.clear();

			mysql_free_result(pResults);
			m_database.FreeOtherResults();
			return err_DB_NumFieldNotMatch;
		}

		iItem = 0;
		POS *pPOS = new POS;
		pPOS->csID = LPSTR(row[iItem++]); 
		pPOS->csPCID = LPSTR(row[iItem++]); 
		pPOS->csPCMAC = LPSTR(row[iItem++]); 
		vctPOS.push_back(pPOS);
	} 
	mysql_free_result(pResults);
	m_database.FreeOtherResults();

	if (m_database.ProcedureGetOutParam("totalNum", adInteger, &dwTotalNum) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());

		for (unsigned int i = 0; i < vctPOS.size(); i++)
		{
			delete vctPOS[i];
			vctPOS[i] = NULL;
		}
		vctPOS.clear();
		return err_DB_Proc_Execute;
	}
	if (m_database.ProcedureGetOutParam("totalPage", adInteger, &dwTotalPage) != TRUE)
	{
		g_log.Write(m_database.GetLastErrorMsg());

		for (unsigned int i = 0; i < vctPOS.size(); i++)
		{
			delete vctPOS[i];
			vctPOS[i] = NULL;
		}
		vctPOS.clear();
		return err_DB_Proc_Execute;
	}

	return err_OK;
}
Exemple #27
0
int db_opw_detail(OPW_HEADER *hd, OPW_DETAIL_REQ *req, OPW_RESULT *rd, OPW_DETAIL_INFO *out)
{
	int ret = E_NO_ERR ;

	char sql[SQL_SIZE] = {'\0'} ;

	int cnt = 0, n;
	MYSQL *conn = NULL ;
	MYSQL_RES *res_set = NULL ;
	MYSQL_ROW row = NULL ;
	int i ;
	int len = 0 ;

	char fmcode[D_FMCODE_SIZE+1] = "" ;
	char gn_time[D_GN_TIME_SIZE+1] = "" ;
	char address[D_ADDRESS_SIZE+1] = "" ;

	char admcode[D_ADMCODE_SIZE+1] = "" ;
	char city[D_ADDR_NAME_SIZE+1] = "" ;
	char gu[D_ADDR_NAME_SIZE+1] = "" ;
	char dong[D_ADDR_NAME_SIZE+1] = "" ;
	char ri[D_ADDR_NAME_SIZE+1] = "" ;

//	ret = mydbc_init(&conn);
//	if(ret != DB_SUCCESS) {
//		printLog(HEAD, "ERR: (%d) mydbc_init[%d]\n", hd->mdn, ret);
//		ret = E_NOT_CONN_DB ;
//		goto error_exit ;
//	}
	conn = mysql_init(NULL) ;
	if(mysql_real_connect(conn, Config.DB_HOST, 
			Config.DB_USER, Config.DB_PASSWORD, Config.DB_NAME, atoi(Config.DB_PORT), NULL, 0) == NULL) {
		printLog(HEAD, "ERR: mysql_real_connect\n") ;
		ret = E_NOT_CONN_DB ;
		goto error_exit ;
	}

	memset(sql, 0, sizeof(sql)) ;
//: 구 제니큐 
//	sprintf(sql, "select jname, pole, g_price, k_price, d_price, l_price, "
//		"date_format(update_time, '%%Y%%m%%d'), date_format(update_time, '%%H%%i%%s'), "
//		"tel, sido, gugun, dong, addr, location, service, map_x, map_y from TSmain where j_id = %ld ", req->id);
//: OPINET
//:		pole->FMCODE
	sprintf(sql, "select NAME, FMCODE, GN_PRICE, DN_PRICE, LPG_PRICE, "
		"GN_TIME, "
		"TEL, ADDRESS, ADMCODE, SVC_TEXT, ETC, XPOS, YPOS from T_OIL_SERVICE where POI_ID=%ld ", req->id);
	printLog(HEAD, "(%d) sql(%s)\n", hd->mdn, sql) ;

//	ret = mydbc_execute_get_result(&conn, sql, &cnt, &res_set);
	ret = mysql_query(conn, sql) ;
	if(ret == DB_SUCCESS) {
		res_set = mysql_store_result(conn) ;
		if(res_set == NULL) ret = E_BAD_SQL ;
		else cnt = (int) mysql_num_rows(res_set) ;
	}

	if(ret != DB_SUCCESS) {
		printLog(HEAD, "ERR: (%d) mydbc_exectue_get_result:[%d]\n", hd->mdn, ret);
		ret = E_BAD_SQL ;
		goto error_exit ;
	}
    if(cnt == 0) {
	    printLog(HEAD, "ERR: (%d) Not Exist j_id(%d)\n", hd->mdn, req->id) ;
        ret = E_NO_DATA ;
        goto error_exit ;
    }

	for(i = 0; i<cnt; i++) {
		if((row = mydbc_next_row(&res_set)) == NULL) break;
		n = -1;
		if(row[++n] != NULL) strncpy(out->name, row[n], D_SERVICE_SIZE);
		//----
	//	if(row[++n] != NULL) out->pole = atoi(row[n]) ;
		if(row[++n] != NULL) strncpy(fmcode, row[n], D_FMCODE_SIZE) ;
		out->pole = fmcode2pole(fmcode) ;
		//----
		if(row[++n] != NULL) out->g_price = atoi(row[n]) ;
		if(row[++n] != NULL) out->k_price = atoi(row[n]) ;
	//	if(row[++n] != NULL) out->d_price = atoi(row[n]) ;		//등유정보가 없음->휘발유고급으로 할지는 생각해볼 사항
		if(row[++n] != NULL) out->l_price = atoi(row[n]) ;
		//---
	//	if(row[++n] != NULL) out->update_date = atoi(row[n]) ;
	//	if(row[++n] != NULL) out->update_time = atoi(row[n]) ;
		if(row[++n] != NULL) strncpy(gn_time, row[n], D_GN_TIME_SIZE) ;
		timeStr2DateTime(gn_time, &(out->update_date), &(out->update_time)) ;	
		printLog(HEAD, "DEBUG: update_date(%d) update_time(%d)\n", out->update_date, out->update_time) ;
		//---
		if(row[++n] != NULL) strncpy(out->tel, row[n], D_TELL_SIZE) ;
		//---
	//	if(row[++n] != NULL) strncpy(out->sido, row[n], D_SIDO_SIZE) ;
	//	if(row[++n] != NULL) strncpy(out->gugun, row[n], D_GUGUN_SIZE) ;
	//	if(row[++n] != NULL) strncpy(out->dong, row[n], D_DONG_SIZE) ;
	//	if(row[++n] != NULL) strncpy(out->etc_addr, row[n], D_ETC_ADDR_SIZE) ;
		if(row[++n] != NULL) strncpy(address, row[n], D_ADDRESS_SIZE) ;
		if(row[++n] != NULL) strncpy(admcode, row[n], D_ADMCODE_SIZE) ;

		db_admcode2address(hd, admcode, city, gu, dong, ri) ;
		strncpy(out->sido, city, D_SIDO_SIZE) ;
		strncpy(out->gugun, gu, D_GUGUN_SIZE) ;
	//	strncpy(out->dong, dong, D_DONG_SIZE) ;
	//	strncat(out->dong, ri, D_ADDR_NAME_SIZE) ;
		sprintf(out->dong, "%s %s", dong, ri) ;

		len = strlen(address) ;
		if(len) {
			FindJibun(address, len, out->etc_addr) ;
		}
		//---
		if(row[++n] != NULL) strncpy(out->service, row[n], D_SERVICE_SIZE) ;
		if(row[++n] != NULL) strncpy(out->location, row[n], D_LOCATION_SIZE) ;
		if(row[++n] != NULL) out->x = atoi(row[n]) ;
		if(row[++n] != NULL) out->y = atoi(row[n]) ;
	}

error_exit :
//	mydbc_free_result(&res_set) ;
	mysql_free_result(res_set) ;

	rd->res_code = ret ;
	rd->total_num = cnt ;
	rd->search_num = cnt ;

	mysql_close(conn) ;
//	ret = mydbc_end(&conn);
//	if(ret != DB_SUCCESS) {
//		printLog(HEAD, "ERR: mydbc_end[%d]\n", ret);
//	}
	return ret ;
}
Exemple #28
0
int main()
{
	//mysql variables
	MYSQL mysql;
  MYSQL_RES *result;
  MYSQL_ROW row;
  string query;
	
	//initiate mysql
	if (!mysql_init(&mysql))
  {
    cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
    return -1;
  }
  cout << "MySQL initialized." << endl;
  
  //connect to database
  if(!mysql_real_connect(&mysql, "assassins.myprotosite.com", "assassins", "password", "assassins", 0, NULL, 0))
  {
    cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
  	return -1;
  }
  cout << "Connected to database." << endl;
  
	while(true)
	{
		pop p(false);
		p.Connect(MAILHOST);
		p.Login(MAILUSER,MAILPASS);
		if(p.NumUnread() > 0)
		{
			p.Retrieve();
			string from = p.GetFrom();
			cout << "Message from: " << from << endl;
			string message_text = p.GetMessageText();
			message_text = StringToLower(message_text);
			cout << "Message text: '" << message_text << "'" << endl;
			
			
			if(message_text.compare("verify") == 0)
			{
				//they are verifying their number
				//look up phone number in SQL table
				string phone_number = from.substr(0, 10);
				
				cout << "Phone number " << phone_number << " wants to verify. Finding user and updating." << endl;
				
				query = "UPDATE users SET mobile='" + from + "' WHERE mobile='" + phone_number + "';";
		    if(mysql_query(&mysql, query.c_str()))
		    {
	    		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
		      return -1;
		    }
			}
			
			if(message_text.compare("status") == 0)
			{
				//they want to know their current status
				string userid;
				
				query = "SELECT * FROM users WHERE mobile='" + from + "';";
		    if(mysql_query(&mysql, query.c_str()))
		    {
	    		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
		      return -1;
		    }
		    
		    result = mysql_store_result(&mysql);
				if(row = mysql_fetch_row(result))
				{
					userid = row[USERID];
				}
				mysql_free_result(result);
				
				notifyNewContract(userid, true);
			}
			
			if(message_text.length() >= 6)
			{
				if(message_text.substr(0, 6).compare("report") == 0)
				{
					if(message_text.length() >= 13)
					{
						//they want to report a kill
						
				    string userid;
				    string targetid;
				    string targetsecret;
				    string newtarget;
				    string gameid;
						string secret = message_text.substr(7, 6);
						cout << "'" << secret << "'" << endl;
						
						query = "SELECT * FROM users WHERE mobile='" + from + "';";
				    if(mysql_query(&mysql, query.c_str()))
				    {
			    		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
				      return -1;
				    }
				    
				    result = mysql_store_result(&mysql);
						if(row = mysql_fetch_row(result))
						{
							userid = row[USERID];
							targetid = row[TARGETID];
							gameid = row[GAMEID];
						}
						mysql_free_result(result);
						
						query = "SELECT * FROM users WHERE userid='" + targetid + "';";
				    if(mysql_query(&mysql, query.c_str()))
				    {
			    		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
				    	return -1;
				    }
				    
				    result = mysql_store_result(&mysql);
						if(row = mysql_fetch_row(result))
						{
							targetsecret = StringToLower(row[SECRET]);
							newtarget = row[TARGETID];
						}
						mysql_free_result(result);
						
						if(targetsecret.compare(secret) == 0)
						{
							//secret is correct, kill confirmed
							
							query = "UPDATE users SET targetid='-1' WHERE userid='" + targetid + "';";
							if(mysql_query(&mysql, query.c_str()))
							{
						  	cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
							 	return -1;
							}
							
							query = "SELECT * FROM users WHERE targetid='-2';";
						  if(mysql_query(&mysql, query.c_str()))
						  {
					   		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
						    return -1;
						  }
						  
						  result = mysql_store_result(&mysql);
							if(row = mysql_fetch_row(result))
							{
								//people are waiting for assignments
								string awaitingid = row[USERID];
								
								query = "UPDATE users SET targetid='" + newtarget + "' WHERE userid='" + awaitingid + "';";
							  if(mysql_query(&mysql, query.c_str()))
							  {
						   		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
							    return -1;
							  }
							  notifyNewContract(awaitingid);
								
								query = "UPDATE users SET targetid='" + awaitingid + "' WHERE userid='" + userid + "';";
							  if(mysql_query(&mysql, query.c_str()))
							  {
						   		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
							    return -1;
							  }
							}
							else
							{
								//no one's waiting for assignment
								
								if(newtarget.compare(userid) != 0)
								{
									query = "UPDATE users SET targetid='" + newtarget + "' WHERE userid='" + userid + "';";
								  if(mysql_query(&mysql, query.c_str()))
								  {
							   		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
								    return -1;
								  }
								}
								else
								{
									//if the target's contract was you, you cannot kill yourself and progress through the game
									//	therefore we must wait for the next kill. when this kill occurs, you will switch contracts
									//	with the person that made the following kill. also, this bracket of code will only run if
									//	there is already no one waiting for assignement, so we dont need to check for that. set target
									//	to -2 to imply awaiting assignment
									
									query = "UPDATE users SET targetid='-2' WHERE userid='" + userid + "';";
								  if(mysql_query(&mysql, query.c_str()))
								  {
							   		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
								    return -1;
								  }
								}
							}
							
							//text back telling kill was reported
						  //mail(from, "Kill Reported."); //redundant. if the user is texting the daemon, phone is enabled, therefore
						  //															//		phone will will receive new contract notice.
							
							//check to see if you're last man standing
							query = "SELECT * FROM users WHERE targetid<>-1 AND gameid='" + gameid + "';";
						  if(mysql_query(&mysql, query.c_str()))
						  {
					   		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
						    return -1;
						  }
						  result = mysql_store_result(&mysql);
							if(mysql_num_rows(result) == 1)
							{
								//you won
								query = "UPDATE users SET targetid='-3' WHERE userid='" + userid + "'";
							  if(mysql_query(&mysql, query.c_str()))
							  {
						   		cout << mysql_errno(&mysql) << ": " << mysql_error(&mysql) << endl;
							    return -1;
							  }
							}
							
							notifyNewContract(userid);
							notifyNewContract(targetid);
						}
						else
						{
							//secret not correct
						  mail(from, "Secret was incorrrect.");
						}
					}
				}
			}
			
			p.Delete();
		}
		p.Close();
		sleep(5);
	}
	
	return 0;
}
Exemple #29
0
int db_opw_sainfo(OPW_HEADER *hd, OPW_SAINFO_REQ *req, OPW_RESULT *rd, OPW_SA_INFO **out)
{
	int ret = E_NO_ERR ;
	
	char sql[BIG_SQL_SIZE] = {'\0'} ;
	char where_saname[BIG_SQL_SIZE] = {'\0'} ;
	char fmcode[D_FMCODE_SIZE+1] = "" ;
	char gn_time[D_GN_TIME_SIZE+1] = "" ;

	int i, n, cnt = 0 ;
	int valid_cnt = 0 ;
	int k = 0 ;

	time_t tt ;

	MYSQL *conn = NULL ;
	MYSQL_RES *res_set = NULL ;
	MYSQL_ROW row = NULL ;

	OPW_SA_INFO *data = NULL ;

	conn = mysql_init(NULL) ;
	if(mysql_real_connect(conn, Config.DB_HOST, 
			Config.DB_USER, Config.DB_PASSWORD, Config.DB_NAME, atoi(Config.DB_PORT), NULL, 0) == NULL) {
		printLog(HEAD, "ERR: mysql_real_connect\n") ;
		ret = E_NOT_CONN_DB ;
		goto error_exit ;
	}	

	
	memset(sql, 0, sizeof(sql)) ;
	memset(where_saname, 0, sizeof(where_saname)) ;

	make_where_sa(req, where_saname);


	sprintf(sql, "select t1.POI_ID, t1.NAME, t2.SAName, t1.FMCODE, t1.GN_PRICE, t1.DN_PRICE, t1.LPG_PRICE, "
			"t1.GN_TIME, "
			"t1.XPOS, t1.YPOS from T_OIL_SERVICE t1, T_OIL_SAINFO t2 %s group by t1.POI_ID order by t2.SAName, t1.FMCODE;", 
			where_saname);
	printLog(HEAD, "sql(%s)\n", sql) ;

//	ret = mydbc_execute_get_result(&conn, sql, &cnt, &res_set);
	ret = mysql_query(conn, sql) ;
	if(ret == DB_SUCCESS) {
		res_set = mysql_store_result(conn) ;
		if(res_set == NULL) ret = E_BAD_SQL ;
		else cnt = (int) mysql_num_rows(res_set) ;
	}

	if(ret != DB_SUCCESS) {
		if(data != NULL) free(data), data=NULL ;
		ret = E_BAD_SQL ;
		goto error_exit ;
	}

	if(cnt == 0) {
		printLog(HEAD, "ERR: (%d) NO DATA ABOUT T_OIL_SERVICE\n", hd->mdn) ;
		ret = E_NO_DATA ;
		goto error_exit ;
	}

	if((data = (OPW_SA_INFO *) malloc (sizeof(OPW_SA_INFO) * cnt)) == NULL) {
		printLog(HEAD, "ERR: Fatal Memory Alloc Fail\n") ;
		ret = E_MEM_ALLOC ;
		goto error_exit ;
	}
	memset(data, 0, sizeof(OPW_SA_INFO) * cnt) ;

	for(i = 0 ; i < cnt ; i++) {
		if((row = mydbc_next_row(&res_set)) == NULL) break;
		n = -1;
		if(row[++n] != NULL) data[i].id = atoi(row[n]) ;
		if(row[++n] != NULL) strncpy(data[i].name, row[n], D_NAME_SIZE) ;
		if(row[++n] != NULL) strncpy(data[i].SAname, row[n], D_SANAME_SIZE) ;
		//--
	//	if(row[++n] != NULL) buf[i].pole = atoi(row[n]) ;
		memset(fmcode, 0, sizeof(fmcode)) ;
		if(row[++n] != NULL) strncpy(fmcode, row[n], D_FMCODE_SIZE) ;
		data[i].pole = fmcode2pole(fmcode) ;

	//	printLog(HEAD, "DEBUG: fmcode[%s]==>pole(%d)\n", fmcode, buf[i].pole) ;

		//--	
	//	if(buf[i].pole == 14) buf[i].pole = 1 ;		//: SK인천정유 주유소(14)->SK(1)
	//	if(buf[i].pole == 15) buf[i].pole = 7 ;		//: SK인천 GAS(15)->SK GAS(7)	

		
		if(row[++n] != NULL) {
			data[i].g_price = atoi(row[n]) ;
		}
		if(row[++n] != NULL) {
			data[i].k_price = atoi(row[n]) ;
		}
		if(row[++n] != NULL) {
			data[i].l_price = atoi(row[n]) ;
		}
		//-
		memset(gn_time, 0, sizeof(gn_time)) ;
		if(row[++n] != NULL) strncpy(gn_time, row[n], D_GN_TIME_SIZE) ;
		timeStr2DateTime(gn_time, &(data[i].update_date), &(data[i].update_time)) ;	
		//-
		if(row[++n] != NULL) data[i].x = atoi(row[n]) ;
		if(row[++n] != NULL) data[i].y = atoi(row[n]) ;
	}


	for(i= 0, n=0 ; n < cnt ; n++) {
		printLog(HEAD, "[%d] id(%d)name(%.52s)SAname(%.60s)pole(%d)g(%d)k(%d)d(%d)l(%d)date(%d)time(%d)x(%d)y(%d)\n",
			i+1, data[i].id, data[i].name, data[i].SAname, data[i].pole, 
			data[i].g_price, data[i].k_price, data[i].d_price, data[i].l_price, 
			data[i].update_date, data[i].update_time, 
			data[i].x, data[i].y) ;

		data[i].id = htonl(data[i].id) ;
		data[i].pole = htonl(data[i].pole) ;
		if(data[i].g_price < 100) data[i].g_price = 0 ;
		data[i].g_price = htons(data[i].g_price) ;
		if(data[i].k_price < 100) data[i].k_price = 0 ;
		data[i].k_price = htons(data[i].k_price) ;
		if(data[i].d_price < 100) data[i].d_price = 0 ;
		data[i].d_price = htons(data[i].d_price) ;
		if(data[i].l_price < 100) data[i].l_price = 0 ;
		data[i].l_price = htons(data[i].l_price) ;
		data[i].update_date = htonl(data[i].update_date) ;
		data[i].update_time = htonl(data[i].update_time) ;
		data[i].x = htonl(data[i].x) ;
		data[i].y = htonl(data[i].y) ;
		i++ ;
	}

	*out = data;

error_exit:
//	mydbc_free_result(&res_set) ;
	mysql_free_result(res_set) ;


	rd->res_code = ret ;
//	rd->total_num = cnt ;
	rd->total_num = cnt ;
	rd->search_num = cnt ;

	mysql_close(conn) ;
	return ret ;
}
Exemple #30
0
void Adventure::MoveCorpsesToGraveyard()
{
	if(GetTemplate()->graveyard_zone_id == 0)
	{
		return;
	}

	list<uint32> dbid_list;
	list<uint32> charid_list;
	char errbuf[MYSQL_ERRMSG_SIZE];
	char* query = 0;
	MYSQL_RES *result;
	MYSQL_ROW row;

	if(database.RunQuery(query,MakeAnyLenString(&query,"SELECT id, charid FROM player_corpses WHERE instanceid=%d", GetInstanceID()), errbuf, &result)) 
	{
		while((row = mysql_fetch_row(result))) 
		{
			dbid_list.push_back(atoi(row[0]));
			charid_list.push_back(atoi(row[1]));
		}
		mysql_free_result(result);
		safe_delete_array(query);
	}
	else
	{
		LogFile->write(EQEMuLog::Error, "Error in AdventureManager:::MoveCorpsesToGraveyard: %s (%s)", query, errbuf);
		safe_delete_array(query);
	}

	list<uint32>::iterator iter = dbid_list.begin();
	while(iter != dbid_list.end())
	{
		float x = GetTemplate()->graveyard_x + MakeRandomFloat(-GetTemplate()->graveyard_radius, GetTemplate()->graveyard_radius);
		float y = GetTemplate()->graveyard_y + MakeRandomFloat(-GetTemplate()->graveyard_radius, GetTemplate()->graveyard_radius);
		float z = GetTemplate()->graveyard_z;
		if(database.RunQuery(query,MakeAnyLenString(&query, "UPDATE player_corpses SET zoneid=%d, instanceid=0, x=%f, y=%f, z=%f WHERE instanceid=%d", 
			GetTemplate()->graveyard_zone_id, x, y, z, GetInstanceID()), errbuf)) 
		{
			safe_delete_array(query);
		}
		else
		{
			LogFile->write(EQEMuLog::Error, "Error in AdventureManager:::MoveCorpsesToGraveyard: %s (%s)", query, errbuf);
			safe_delete_array(query);
		}
		iter++;
	}

	iter = dbid_list.begin();
	list<uint32>::iterator c_iter = charid_list.begin();
	while(iter != dbid_list.end())
	{
		ServerPacket* pack = new ServerPacket(ServerOP_DepopAllPlayersCorpses, sizeof(ServerDepopAllPlayersCorpses_Struct));
		ServerDepopAllPlayersCorpses_Struct *dpc = (ServerDepopAllPlayersCorpses_Struct*)pack->pBuffer;
		dpc->CharacterID = (*c_iter);
		dpc->InstanceID = 0;
		dpc->ZoneID = GetTemplate()->graveyard_zone_id;
		zoneserver_list.SendPacket(0, GetInstanceID(), pack);
		delete pack;

		pack = new ServerPacket(ServerOP_SpawnPlayerCorpse, sizeof(SpawnPlayerCorpse_Struct));
		SpawnPlayerCorpse_Struct* spc = (SpawnPlayerCorpse_Struct*)pack->pBuffer;
		spc->player_corpse_id = (*iter);
		spc->zone_id = GetTemplate()->graveyard_zone_id;

		zoneserver_list.SendPacket(spc->zone_id, 0, pack);
		delete pack;
		iter++;
		c_iter++;
	}
}