Exemple #1
0
int main( int iArgc, char* pszArgV[] )
{
	if( mysql_library_init( 0, nullptr, nullptr ) )
	{
		std::cout << "Failed to initialize MySQL" << std::endl;

		std::cin.get();

		return EXIT_FAILURE;
	}

	CASManager manager;

	bool bSuccess = false;

	{
		CASInitializer initializer;

		bSuccess = manager.Initialize( initializer );
	}

	if( bSuccess )
	{
		std::cout << "Starting tests" << std::endl;

		manager.GetModuleManager().AddDescriptor( "Test", 0xFFFFFFFF, as::ModulePriority::HIGHEST );

		CASModuleBuilder builder;

		if( CASModule* pModule = manager.GetModuleManager().BuildModule( "Test", "Test", builder ) )
		{
			if( auto pFunction = pModule->GetModule()->GetFunctionByDecl( "void main()" ) )
			{
				as::Call( pFunction );

				CASOwningContext ctx( *manager.GetEngine() );

				bool bDidWork = false;

				do
				{
					bDidWork = g_ASSQL.GetThreadPool().ProcessQueue( *ctx.GetContext() );

					std::this_thread::yield();
				}
				while( bDidWork || g_ASSQL.GetThreadPool().ThreadsActive() || g_ASSQL.GetThreadPool().GetThreadQueue().GetQueueSize() > 0 );

				g_ASSQL.GetThreadPool().Stop( true );

				g_ASSQL.GetThreadPool().GetThreadQueue().Clear();

				std::cout << g_ASSQL.GetThreadPool().GetThreadQueue().GetQueueSize() << " items left in the queue" << std::endl;
			}
			else
			{
				std::cout << "Couldn't find main function" << std::endl;
			}
		}
		else
		{
			std::cout << "Couldn't build module" << std::endl;
		}
	}

	manager.Shutdown();

	std::cout << "Finished running tests" << std::endl;

	mysql_library_end();

	std::cin.get();

	return bSuccess ? EXIT_SUCCESS : EXIT_FAILURE;
}
Exemple #2
0
int main(int argc, char *argv[]) {
	struct configuration conf= { NULL, NULL, NULL, 0 };

	GError *error= NULL;
	GOptionContext *context;

	g_thread_init(NULL);

	init_mutex= g_mutex_new();

	if(db == NULL && source_db != NULL){
		db = g_strdup(source_db);
	}

	context= g_option_context_new("multi-threaded MySQL loader");
	GOptionGroup *main_group= g_option_group_new("main", "Main Options", "Main Options", NULL, NULL);
	g_option_group_add_entries(main_group, entries);
	g_option_group_add_entries(main_group, common_entries);
	g_option_context_set_main_group(context, main_group);
	if (!g_option_context_parse(context, &argc, &argv, &error)) {
		g_print("option parsing failed: %s, try --help\n", error->message);
		exit(EXIT_FAILURE);
	}
	g_option_context_free(context);

	//prompt for password if it's NULL
	if ( sizeof(password) == 0 || ( password == NULL && askPassword ) ){
		password = passwordPrompt();
	}

	if (program_version) {
		g_print("myloader %s, built against MySQL %s\n", VERSION, MYSQL_VERSION_STR);
		exit(EXIT_SUCCESS);
	}

	set_verbose(verbose);

	if (!directory) {
		g_critical("a directory needs to be specified, see --help\n");
		exit(EXIT_FAILURE);
	} else {
		char *p= g_strdup_printf("%s/metadata", directory);
		if (!g_file_test(p, G_FILE_TEST_EXISTS)) {
			g_critical("the specified directory is not a mydumper backup\n");
			exit(EXIT_FAILURE);
		}
	}
	MYSQL *conn;
	conn= mysql_init(NULL);

	configure_connection(conn,"myloader");
	if (!mysql_real_connect(conn, hostname, username, password, NULL, port, socket_path, 0)) {
		g_critical("Error connection to database: %s", mysql_error(conn));
		exit(EXIT_FAILURE);
	}

	if (mysql_query(conn, "SET SESSION wait_timeout = 2147483")){
		g_warning("Failed to increase wait_timeout: %s", mysql_error(conn));
	}

	if (!enable_binlog)
		mysql_query(conn, "SET SQL_LOG_BIN=0");

	mysql_query(conn, "/*!40014 SET FOREIGN_KEY_CHECKS=0*/");
	conf.queue= g_async_queue_new();
	conf.ready= g_async_queue_new();

	guint n;
	GThread **threads= g_new(GThread*, num_threads);
	struct thread_data *td= g_new(struct thread_data, num_threads);
	for (n= 0; n < num_threads; n++) {
		td[n].conf= &conf;
		td[n].thread_id= n+1;
		threads[n]= g_thread_create((GThreadFunc)process_queue, &td[n], TRUE, NULL);
		g_async_queue_pop(conf.ready);
	}
	g_async_queue_unref(conf.ready);

	g_message("%d threads created", num_threads);

	restore_databases(&conf, conn);

	for (n= 0; n < num_threads; n++) {
		struct job *j= g_new0(struct job, 1);
		j->type = JOB_SHUTDOWN;
		g_async_queue_push(conf.queue, j);
	}

	for (n= 0; n < num_threads; n++) {
		g_thread_join(threads[n]);
	}

	restore_schema_post(conn);

	restore_schema_view(conn);

	restore_schema_triggers(conn);

	g_async_queue_unref(conf.queue);
	mysql_close(conn);
	mysql_thread_end();
	mysql_library_end();
	g_free(directory);
	g_free(td);
	g_free(threads);

	return errors ? EXIT_FAILURE : EXIT_SUCCESS;
}
GSqlDatabase::~GSqlDatabase(void)
{
	mysql_close(&(this->_mysql));
	mysql_library_end();
}
int main(){
	char * stringToReturn;
	struct http_request request;
	int status;
	MYSQL * conn;
	struct gs_report testReport;

	conn = _getMySQLConnection();
   	if(!conn){
	  	fprintf(stderr, "%s\n", "Could not connect to mySQL");
	  	close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
	  	return 1;
   	}
   	_shared_campaign_id =1 ;
   		
   	gs_report_ZeroStruct(&testReport); 	

   	gs_report_setScopeId(CAMPAIGN_ID, &testReport);
	gs_report_setContent("cc obj/sha256temp.o -o sha256.o -lcrypto\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 10\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 11\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 10\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 11\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 19\n/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':\n(.text+0x20): undefined reference to `main'\ncollect2: ld returned 1 exit status\nmake: *** [sha256.o] Error 1\n",&testReport);
	gs_report_setAuthorize("test",&testReport);
	gs_report_setOrigin("admin",&testReport);
	gs_report_setType("INFO",&testReport);

   	db_insertReport(&testReport,conn);

   	stringToReturn = malloc(1000);
	request.method = DELETE;
	
	/* Valids */
	sprintf(request.url, "/api/debug?origin=%s&hash=%s", "admin", testReport.authorize);
	status = report_controller(&request, &stringToReturn, 1000);
	EXPECTED(204, status, "Request failed to return no content")

	/* Invalids */

	sprintf(request.url, "/api/debug?origin=%s&hash=%s", "admin", testReport.authorize);
	status = report_controller(&request, &stringToReturn, 1000);
	EXPECTED(404, status, "Request failed to return not found status")

	sprintf(request.url, "/api/debug");
	status = report_controller(&request, &stringToReturn, 1000);
	EXPECTED(400, status, "Request failed to err when no params present")	

	sprintf(request.url, "/api/debug?origin=%s", testReport.origin);
	status = report_controller(&request, &stringToReturn, 1000);
	EXPECTED(400, status, "Request failed to err when given only origin")

	sprintf(request.url, "/api/debug?hash=%s", testReport.authorize);
	status = report_controller(&request, &stringToReturn, 1000);
	EXPECTED(400, status, "Request failed to err when given only hash")


	mysql_close(conn);
	mysql_library_end();
		
	free(stringToReturn);
	fflush(stdout);
	fflush(stderr);
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);
	return 0;
}
Exemple #5
0
void MySQLDatabase::Shutdown()
{
	mysql_library_end();
}
Exemple #6
0
int main(){
	char * stringToReturn;
	struct http_request request;
	int status;
	int size;
	MYSQL * conn;
	struct gs_report testReport;

	size = 1000;
	request.method = GET;
	stringToReturn = malloc(size);

	/* 
		Initialize a report to begotten
	*/
	conn = _getMySQLConnection();
   	if(!conn){
	  	fprintf(stderr, "%s\n", "Could not connect to mySQL");
	  	close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);
	  	return 1;
   	}
   	_shared_campaign_id = 1;

	gs_report_ZeroStruct(&testReport);

	gs_report_setScopeId(CAMPAIGN_ID, &testReport);
	gs_report_setContent("cc obj/sha256temp.o -o sha256.o -lcrypto\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 0 has invalid symbol index 10\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 1 has invalid symbol index 11\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 2 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 3 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 4 has invalid symbol index 10\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 5 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 6 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 7 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 8 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 9 has invalid symbol index 2\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 10 has invalid symbol index 11\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 11 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 12 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 13 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 14 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 15 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 16 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 17 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 18 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 19 has invalid symbol index 12\n/usr/bin/ld: /usr/lib/debug/usr/lib/x86_64-linux-gnu/crt1.o(.debug_info): relocation 20 has invalid symbol index 19\n/usr/lib/gcc/x86_64-linux-gnu/4.6/../../../x86_64-linux-gnu/crt1.o: In function `_start':\n(.text+0x20): undefined reference to `main'\ncollect2: ld returned 1 exit status\nmake: *** [sha256.o] Error 1\n",&testReport);
	gs_report_setAuthorize("test",&testReport);
	gs_report_setOrigin("admin",&testReport);
	gs_report_setType("INFO",&testReport);
	db_insertReport(&testReport, conn);



	sprintf(request.url, "/api/debug");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(200,status, "Failed on non-parameterized pins get.")

	sprintf(request.url, "/api/debug?since=2013-12-13-00:00");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(200,status, "Failed on ?since= get.")

	sprintf(request.url, "/api/debug?page=1");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(200,status, "Failed on ?page= get.")

	sprintf(request.url, "/api/debug?since=2013-12-13-00:00");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(200,status, "Should have succeeded with valid since parameter")

	sprintf(request.url, "/api/debug?hash=%s", testReport.authorize);
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(200,status, "Should have succeeded with valid hash to retrieve")

	sprintf(request.url, "/api/debug?since=2013-12-13-00:00&page=1");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(200,status, "Should have succeeded with page and since parameters")	

	/* 4xx */

	sprintf(request.url, "/api/debug?hash=404value");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(404,status, "Should not have found any report by this hash")

	sprintf(request.url, "/api/debug?hash=3&page=1");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(422,status, "Hash and page parameters should be mutually exclusive")	

	sprintf(request.url, "/api/debug?since=2013-12-13-00:00&page=failed");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(422,status, "Should fail with invalid page parameter")	 /* 422? why not 400, spec you so crazy */

	sprintf(request.url, "/api/debug?since=2013-1e-13a00:00");
	status = report_controller(&request, &stringToReturn, size);
	EXPECTED(400,status, "Should not have parsed since time")	


	mysql_close(conn);
	mysql_library_end();

	free(stringToReturn);
	fflush(stdout);
	fflush(stderr);
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);
	return 0;
}
Exemple #7
0
int main(int argc, char** argv)
{
	if(argc < 3){
		fprintf(stderr,"Usage: classify <input> <expected output>");
		return 1;
	}
	int rd = 0,buffsz = getpagesize(),strsz = 0,ex_val = 0;
	char buffer[1024], *strbuff = (char*)calloc(buffsz,sizeof(char));
	FILE *input,*expected;

	if(mysql_library_init(num_elements, server_options, server_groups))
		{
			printf("Error: Cannot initialize Embedded Library.");
		    return 1;
		}

	input = fopen(argv[1],"rb");

    if(input == NULL)
    {
        printf("Error: Failed to open input file %s", argv[1]);
        return 1;
    }
    
	expected = fopen(argv[2],"rb");

    if(expected == NULL)
    {
        fclose(input);
        printf("Error: Failed to open expected output file %s", argv[2]);
        return 1;
    }

	while((rd = fread(buffer,sizeof(char),1023,input))){
		
		/**Fill the read buffer*/

		if(strsz + rd >= buffsz){

			char* tmp = realloc(strbuff,(buffsz*2)*sizeof(char));
			
			if(tmp == NULL){
				free(strbuff);
				fclose(input);
				fclose(expected);
				mysql_library_end();
				fprintf(stderr,"Error: Memory allocation failed.");
				return 1;
			}
			strbuff = tmp;
			buffsz *= 2;
		}
		
		memcpy(strbuff+strsz,buffer,rd);
		strsz += rd;
		*(strbuff+strsz) = '\0';

		char *tok,*nlptr;

		/**Remove newlines*/
		while((nlptr = strpbrk(strbuff,"\n")) != NULL && (nlptr - strbuff) < strsz){
			memmove(nlptr,nlptr+1,strsz - (nlptr + 1 - strbuff));
			strsz -= 1;
		}


		/**Parse read buffer for full queries*/

		while(strpbrk(strbuff,";") != NULL){
			tok = strpbrk(strbuff,";");
			unsigned int qlen = tok - strbuff + 1;
			GWBUF* buff = gwbuf_alloc(qlen+6);
			*((unsigned char*)(buff->start)) = qlen;
			*((unsigned char*)(buff->start + 1)) = (qlen >> 8);
			*((unsigned char*)(buff->start + 2)) = (qlen >> 16);
			*((unsigned char*)(buff->start + 3)) = 0x00;
			*((unsigned char*)(buff->start + 4)) = 0x03;
			memcpy(buff->start+5, strbuff, qlen);
			memmove(strbuff,tok + 1, strsz - qlen);
			strsz -= qlen;
			memset(strbuff + strsz,0,buffsz - strsz);
			skygw_query_type_t type = query_classifier_get_type(buff);
			char qtypestr[64];
			char expbuff[256];
			int expos = 0;
			
			while((rd = fgetc(expected)) != '\n' && !feof(expected)){
				expbuff[expos++] = rd;
			}
			expbuff[expos] = '\0';

			if(type == QUERY_TYPE_UNKNOWN){
				sprintf(qtypestr,"QUERY_TYPE_UNKNOWN");
			}
			if(type & QUERY_TYPE_LOCAL_READ){
				sprintf(qtypestr,"QUERY_TYPE_LOCAL_READ");
			}
			if(type & QUERY_TYPE_READ){
				sprintf(qtypestr,"QUERY_TYPE_READ");
			}
			if(type & QUERY_TYPE_WRITE){
				sprintf(qtypestr,"QUERY_TYPE_WRITE");
			}
			if(type & QUERY_TYPE_MASTER_READ){
				sprintf(qtypestr,"QUERY_TYPE_MASTER_READ");
			}
			if(type & QUERY_TYPE_SESSION_WRITE){
				sprintf(qtypestr,"QUERY_TYPE_SESSION_WRITE");
			}
			if(type & QUERY_TYPE_USERVAR_READ){
				sprintf(qtypestr,"QUERY_TYPE_USERVAR_READ");
			}
			if(type & QUERY_TYPE_SYSVAR_READ){
				sprintf(qtypestr,"QUERY_TYPE_SYSVAR_READ");
			}
			if(type & QUERY_TYPE_GSYSVAR_READ){
				sprintf(qtypestr,"QUERY_TYPE_GSYSVAR_READ");
			}
			if(type & QUERY_TYPE_GSYSVAR_WRITE){
				sprintf(qtypestr,"QUERY_TYPE_GSYSVAR_WRITE");
			}
			if(type & QUERY_TYPE_BEGIN_TRX){
				sprintf(qtypestr,"QUERY_TYPE_BEGIN_TRX");
			}
			if(type & QUERY_TYPE_ENABLE_AUTOCOMMIT){
				sprintf(qtypestr,"QUERY_TYPE_ENABLE_AUTOCOMMIT");
			}
			if(type & QUERY_TYPE_DISABLE_AUTOCOMMIT){
				sprintf(qtypestr,"QUERY_TYPE_DISABLE_AUTOCOMMIT");
			}
			if(type & QUERY_TYPE_ROLLBACK){
				sprintf(qtypestr,"QUERY_TYPE_ROLLBACK");
			}
			if(type & QUERY_TYPE_COMMIT){
				sprintf(qtypestr,"QUERY_TYPE_COMMIT");
			}
			if(type & QUERY_TYPE_PREPARE_NAMED_STMT){
				sprintf(qtypestr,"QUERY_TYPE_PREPARE_NAMED_STMT");
			}
			if(type & QUERY_TYPE_PREPARE_STMT){
				sprintf(qtypestr,"QUERY_TYPE_PREPARE_STMT");
			}
			if(type & QUERY_TYPE_EXEC_STMT){
				sprintf(qtypestr,"QUERY_TYPE_EXEC_STMT");
			}
			if(type & QUERY_TYPE_CREATE_TMP_TABLE){
				sprintf(qtypestr,"QUERY_TYPE_CREATE_TMP_TABLE");
			}
			if(type & QUERY_TYPE_READ_TMP_TABLE){
				sprintf(qtypestr,"QUERY_TYPE_READ_TMP_TABLE");
			}
			
			if(strcmp(qtypestr,expbuff) != 0){
				printf("Error in output: '%s' was expected but got '%s'",expbuff,qtypestr);
				ex_val = 1;
			}
			
			gwbuf_free(buff);			
		}
	}
	fclose(input);
	fclose(expected);
	mysql_library_end();
	free(strbuff);
	return ex_val;
}
int main(int argc, char** argv)
{
        slist_cursor_t*    c;
        const char*        q;
        query_test_t*      qtest;
        skygw_query_type_t qtype;
        bool               succp;
        bool               failp = true;
        unsigned int       f = 0;
        int                nsucc = 0;
        int                nfail = 0;
        MYSQL*             mysql;
        char*              workingdir;
        char               ddoption[1024];

        ss_dfprintf(stderr, ">> testmain\n");
        c = slist_init();

        /** Test some functions */
        q = "SELECT MY_UDF('Hello')";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        /** This could be QUERY_TYPE_LOCAL_READ */
        q = "SELECT repeat('a', 1024)";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_READ, false, true));

        /** This could be QUERY_TYPE_LOCAL_READ */
        q = "SELECT soundex('Hello')";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_READ, false, true));

        q = "SELECT ssoundexx('Hello')";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        /** This could be QUERY_TYPE_LOCAL_READ */
        q = "SELECT now()";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_READ, false, true));

        /** This could be QUERY_TYPE_LOCAL_READ */
        q = "SELECT rand()";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_READ, false, true));

        q = "SELECT rand(234), MY_UDF('Hello'), soundex('Hello')";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        
        /** Read-only SELECTs */
        q = "SELECT user from mysql.user";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_READ, false, true));

        q = "select tt1.id, tt2.id from t1 tt1, t2 tt2 where tt1.name is "
            "not null and tt2.name is not null";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_READ, false, false));

        /** SELECT ..INTO clauses > session updates */
        q = "SELECT user from mysql.user INTO DUMPFILE '/tmp/dump1'";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));

        q = "SELECT user INTO DUMPFILE '/tmp/dump2 ' from mysql.user";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));

        q = "SELECT user from mysql.user INTO OUTFILE '/tmp/out1'";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));

        /** Database and table name must be separated by a dot */
        q = "SELECT user INTO OUTFILE '/tmp/out2 ' from mysql-user";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, true, false));

        /** Database and table name must be separated by a dot */
        q = "SELECT user INTO OUTFILE '/tmp/out2 ' from mysql_foo_user";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));
        
        q = "SELECT user FROM mysql.user limit 1 INTO @local_variable";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));

        q = "SELECT user INTO @local_variable FROM mysql.user limit 1";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));
        
        q = "SELECT non_existent_attr INTO @d FROM non_existent_table";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));

        q = "select * from table1 "
            "where table1.field IN "
            "(select * from table1a union select * from table1b) union "
            "select * from table2 where table2.field = "
            "(select (select f1 from table2a where table2a.f2 = table2b.f3) "
            "from table2b where table2b.f1 = table2.f2) union "
            "select * from table3";
            slcursor_add_case(
                    c,
                    query_test_init(q, QUERY_TYPE_READ, false, true));
                
        /** RENAME TABLEs */
        q = "RENAME TABLE T1 to T2";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, false));

        
        /** INSERTs */
        q = "INSERT INTO T1 (SELECT * FROM T2)";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        q = "INSERT INTO T1 VALUES(2, 'foo', 'toomanyattributes')";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        q = "INSERT INTO T2 VALUES(1, 'sthrgey')";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, false));

        q = "INSERT INTO T2 VALUES(8, 'ergstrhe')";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, false));

        q = "INSERT INTO T2 VALUES(9, NULL)";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, false));


        /** Ok, delimeter is client-side parameter which shouldn't be handled
         * on server side.
         */
        q = "delimiter //";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, true, true));

        /** SETs, USEs > Session updates */
        q = "SET @a=1";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, true));
        
        q = "USE TEST";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, false));

        
        /** Object creation statements */
        q = "create procedure si (out param1 int) \nbegin select count(*) "
            "into param1 from t1; \nend";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));
        
        q = "CREATE TABLE T1 (id integer primary key, name varchar(10))";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        q = "DROP TABLE T1";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, false));

        q = "ALTER TABLE T1 ADD COLUMN WHYME INTEGER NOT NULL";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, false));

        q = "TRUNCATE TABLE T1";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, false));

        q = "DROP SERVER IF EXISTS VICTIMSRV";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, true));

        q = "CREATE USER FOO IDENTIFIED BY 'BAR'";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        q = "OPTIMIZE NO_WRITE_TO_BINLOG TABLE T1";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));

        q = "SELECT NOW();CREATE TABLE T1 (ID INTEGER);"
            "SET sql_log_bin=0;CREATE TABLE T2 (ID INTEGER)";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_WRITE, false, true));
        
        
        /** Setting database makes this SESSION_WRITE */
        q = "USE TEST;CREATE TABLE T1 (ID INTEGER);"
            "SET sql_log_bin=0;CREATE TABLE T2 (ID INTEGER)";
        slcursor_add_case(
                c,
                query_test_init(q, QUERY_TYPE_SESSION_WRITE, false, true));
        
        /**
         * Init libmysqld.
         */
        workingdir = getenv("PWD");
        
        if (workingdir == NULL) {
                fprintf(stderr,
                        "Failed to resolve the working directory, $PWD is not "
                        "set.\n");
                goto return_without_server;
        } else if (access(workingdir, R_OK) != 0) {
                fprintf(stderr,
                        "Failed to access the working directory due %d, %s\n",
                        errno,
                        strerror(errno));
                goto return_without_server;
        } else {
                char** so = server_options;
                snprintf(datadir, 1023, "%s/data", workingdir);
                mkdir(datadir, 0777);
                snprintf(ddoption, 1023, "--datadir=%s", datadir);

                while (strncmp(*so++, "--datadir=", 10) != 0) ;

                if (*so == NULL) {
                        fprintf(stderr, "Failed to find datadir option.\n");
                        goto return_without_server;
                }
                *so = ddoption;
                
                snprintf(mysqldir, 1023, "%s/mysql", workingdir);
                setenv("MYSQL_HOME", mysqldir, 1);
        }
        failp = mysql_library_init(num_elements, server_options, server_groups);

        if (failp) {
            MYSQL* mysql = mysql_init(NULL);
            ss_dassert(mysql != NULL);
            fprintf(stderr,
                    "mysql_init failed, %d : %s\n",
                    mysql_errno(mysql),
                    mysql_error(mysql));
            goto return_without_server;
        }

        fprintf(stderr,
                "\nExecuting selected cases in "
                "skygw_query_classifier_get_type :\n\n");
        /**
         * Set cursor to the beginning, scan through the list and execute
         * test cases.
         */
        succp = slcursor_move_to_begin(c);
        
        while(succp) {
            qtest = slcursor_get_case(c);
            qtest->qt_result_type =
                skygw_query_classifier_get_type(qtest->qt_query_str, f);
            succp = slcursor_step_ahead(c);
        }
        /**
         * Scan through test results and compare them against expected
         * results.
         */
        succp = slcursor_move_to_begin(c);
        fprintf(stderr, "\nScanning through the results :\n\n");
        
        while(succp) {
            qtest = slcursor_get_case(c);
            
            if (!query_test_types_match(qtest)) {
                nfail += 1;
                ss_dfprintf(stderr,
                            "* Failed: \"%s\" -> %s (Expected %s)\n",
                            query_test_get_querystr(qtest),
                            STRQTYPE(query_test_get_result_type(qtest)),
                            STRQTYPE(query_test_get_query_type(qtest)));
            } else {
                nsucc += 1;
                ss_dfprintf(stderr,
                            "Succeed\t: \"%s\" -> %s\n",
                            query_test_get_querystr(qtest),
                            STRQTYPE(query_test_get_query_type(qtest)));
            }
            succp = slcursor_step_ahead(c);
        }
        fprintf(stderr,
                "------------------------------------------\n"
                "Tests in total %d, SUCCEED %d, FAILED %d\n",
                nsucc+nfail,
                nsucc,
                nfail);

        /**
         * Scan test results and re-execute those which are marked to be
         * executed also in the server. This serves mostly debugging purposes.
         */
        succp = slcursor_move_to_begin(c);
        mysql = mysql_init(NULL);

        if (mysql == NULL) {
            fprintf(stderr, "mysql_init failed\n");
            goto return_without_server;
        }

        mysql_options(mysql,
                      MYSQL_READ_DEFAULT_GROUP,
                      "libmysqld_client");
        mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);
        mysql_options(mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL);

        mysql = mysql_real_connect(mysql,
                                   NULL,
                                   "skygw",
                                   "skygw",
                                   NULL,
                                   0,
                                   NULL,
                                   CLIENT_MULTI_STATEMENTS);
        
        if (mysql == NULL) {
            fprintf(stderr, "mysql_real_connect failed\n");
            goto return_with_handle;
        }

        fprintf(stderr,
                "\nRe-execution of selected cases in Embedded server :\n\n");
        
        while(succp) {
            qtest = slcursor_get_case(c);

            if (query_test_exec_also_in_server(qtest)) {
                MYSQL_RES*  results;
                MYSQL_ROW   record;
                const char* query_str;
                
                query_str = query_test_get_querystr(qtest);
                failp = mysql_query(mysql, query_str);

                if (failp) {
                    ss_dfprintf(stderr,
                                "* Failed: \"%s\" -> %d : %s\n",
                                query_str,
                                mysql_errno(mysql),
                                mysql_error(mysql));
                } else {
                    ss_dfprintf(stderr,
                                "Succeed\t: \"%s\"\n",
                                query_str);
                    results = mysql_store_result(mysql);
                    
                    if (results != NULL) {
                        
                        while((record = mysql_fetch_row(results))) {
                            while(record != NULL && *record != NULL) {
                                ss_dfprintf(stderr, "%s ", *record);
                                record++;
                            }
                            ss_dfprintf(stderr, "\n");
                        }
                        mysql_free_result(results);
                    }
                }
            }
            succp = slcursor_step_ahead(c);
            
        }
        slist_done(c);
        fprintf(stderr, "------------------------------------------\n");
        
return_with_handle:
        mysql_close(mysql);
        mysql_thread_end();
        mysql_library_end();
        
return_without_server:
        ss_dfprintf(stderr, "\n<< testmain\n");
        fflush(stderr);
        return 0;
}
Exemple #9
0
void Team5_DB::Disconnect()
{
    mysql_close(mysql);
    mysql_library_end();
}
Exemple #10
0
void db_library_end()
{
	mysql_library_end ();
}
void
am_mysql_library_end (void){
  mysql_library_end ();
}
Exemple #12
0
short download_blob_data(char *db_module,char *db_file,char *field_list,char *key_values,char *encoding_type,char *filename)
{
#ifdef USE_MYSQL
	APPlib *sql_fields=NULL,*sql_values=NULL;
	FILE *fp=NULL;
	short err=-1;
	int x=0,y=0,z=0;
	MYSQL *mysql;
	MYSQL_ROW mysqlRow;
	MYSQL_RES *mysqlResult;
	char *temp=NULL,*mytemp;

	unsigned long *lengths;
	unsigned int num_fields;

	unsigned long long rows_returned=0;

	unsigned int db_module_length=0;
	unsigned int db_file_length=0;
	unsigned int field_list_length=0;
	unsigned int key_values_length=0;

	if(db_module==NULL)
	{
		prterr("Error:  db_module is NULL.\n");
		return(-1);
	}
	
	if(db_file==NULL)
	{
		prterr("Error:  db_file is NULL.\n");
		return(-1);
	}
	
	if(field_list==NULL)
	{
		prterr("Error:  field_list is NULL.\n");
		return(-1);
	}
	
	if(key_values==NULL)
	{
		prterr("Error:  key_values is NULL.\n");
		return(-1);
	}

	if(encoding_type==NULL)
	{
		prterr("Error:  encoding_type is NULL.\n");
		return(-1);
	}

	if(filename==NULL)
	{
		prterr("Error:  filename is NULL.\n");
		return(-1);
	}


	db_module_length=strlen(db_module);
	if(db_module_length==0)
	{
		prterr("Error:  db_module is empty.\n");
		return(-1);
	}
	
	db_file_length=strlen(db_file);
	if(db_file_length==0)
	{
		prterr("Error:  db_file is empty.\n");
		return(-1);
	}
	
	field_list_length=strlen(field_list);
	if(field_list_length==0)
	{
		prterr("Error:  field_list is empty.\n");
		return(-1);
	}
	
	key_values_length=strlen(key_values);
	if(key_values_length==0)
	{
		prterr("Error:  key_values is empty.\n");
		return(-1);
	}

	if((strlen(encoding_type))==0)
	{
		prterr("Error:  encoding_type is empty.\n");
		return(-1);
	}

	if((strlen(filename))==0)
	{
		prterr("Error:  filename is empty.\n");
		return(-1);
	}

	mysql=mysql_init(NULL);
	if(!mysql)
	{
		prterr("Error:  Couldn't initialize MYSQL structure.");
	} else {
#ifdef WIN32			
			mysql_options(mysql,MYSQL_READ_DEFAULT_FILE,"rda\\my.cnf");
#else
			mysql_options(mysql,MYSQL_READ_DEFAULT_FILE,"rda/my.cnf");
#endif
			mysql_options(mysql,MYSQL_READ_DEFAULT_GROUP,db_module);
	
		if(!mysql_real_connect(mysql,NULL,NULL,NULL,db_module,0,NULL,0))
		{
			prterr("Error: mysql_real_connect failed for %s->%s with %s.",db_module,db_file,mysql_error(mysql));
			return(err);
		}	
	}
	if(mysql!=NULL)
	{
		mytemp=Rmalloc(field_list_length+key_values_length);
		memset(mytemp,0,(field_list_length+key_values_length));
		sql_fields=APPlibNEW();
		for(x=0;x<field_list_length;x++)
		{
			if((field_list[x]=='|')&&(y==0))
			{
				y=1;
			} else if((field_list[x]=='|')&&(y==1)) {
				strncpy(mytemp,field_list+z,(x-(z+1)));
				addAPPlib(sql_fields,mytemp);
				y=0;
				z=(x+1);
				memset(mytemp,0,(field_list_length+key_values_length));

			} else if(x==(field_list_length-1)) {
				strncpy(mytemp,field_list+z,field_list_length);
				addAPPlib(sql_fields,mytemp);
				memset(mytemp,0,(field_list_length+key_values_length));
			}
		}

#ifdef USE_RDA_DIAGNOSTICS
		if((diagmix)||(diagnrd)||(diagmisc))
		{
			SEEAPPlib(sql_fields);
		}
#endif /* ifdef USE_RDA_DIAGNOSTICS */
		sql_values=APPlibNEW();
		z=0;
		for(x=0;x<key_values_length;x++)
		{
			if((key_values[x]=='|')&&(y==0))
			{
				y=1;
			} else if((key_values[x]=='|')&&(y==1)) {
				strncpy(mytemp,key_values+z,(x-(z+1)));
				addAPPlib(sql_values,mytemp);
				y=0;
				z=(x+1);
				memset(mytemp,0,(field_list_length+key_values_length));
				} else if(x==(key_values_length-1)) {
				strncpy(mytemp,key_values+z,key_values_length);
				addAPPlib(sql_values,mytemp);
				memset(mytemp,0,(field_list_length+key_values_length));
			}
		}
		if(mytemp!=NULL) Rfree(mytemp);

#ifdef USE_RDA_DIAGNOSTICS
		if((diagmix)||(diagnrd)||(diagmisc))
		{
			SEEAPPlib(sql_values);
		}
#endif /* ifdef USE_RDA_DIAGNOSTICS */

		temp=Rmalloc((db_module_length+db_file_length+field_list_length+key_values_length)*2+520);
		memset(temp,0,((db_module_length+db_file_length+field_list_length+key_values_length)*2+520));
		sprintf(temp,"SELECT ");
		for(x=0;x<sql_fields->numlibs;x++) 
		{
			if(x==(sql_fields->numlibs-1))
			{
				sprintf(temp,"%s%s FROM %s ",temp,sql_fields->libs[x],db_file);
			}else{
					sprintf(temp,"%s%s,",temp,sql_fields->libs[x]);
			}
		}
		
		for(x=0;x<sql_values->numlibs;x++) 
		{
			if(x==0)
			{
				sprintf(temp,"%sWHERE (%s = \"%s\" ",temp,sql_fields->libs[x],sql_values->libs[x]);
			}else if(strlen(sql_values->libs[x])!=0) {
				sprintf(temp,"%sAND %s = \"%s\" ",temp,sql_fields->libs[x],sql_values->libs[x]);
			}
		}
		sprintf(temp,"%s)",temp);
		

		if(!mysql_real_query(mysql,temp,RDAstrlen(temp)))
		{
			mysqlResult=mysql_store_result(mysql);
			if(mysqlResult!=NULL)
			{
				rows_returned=mysql_num_rows(mysqlResult);
				if(rows_returned>1) 
				{
					prterr("Error:  More than one row returned.  Returned [%d] rows.  Please check your key information to insure only one row is downloaded.\n",rows_returned);
				}else{
					while((mysqlRow=mysql_fetch_row(mysqlResult)))
					{
						num_fields=mysql_num_fields(mysqlResult);
						lengths = mysql_fetch_lengths(mysqlResult);
	
						/*
						printf("num_fields = [%d]  x = [%d]\n",num_fields,x);
						printf("FILE SIZE = %d\n", lengths[(num_fields-1)]);
						printf("FILE DATA: [\n%s\n",mysqlRow[(num_fields-1)]);
						*/
#ifdef WIN32
						if((stricmp(encoding_type,"RAW"))==0) 
#else
						if((strcasecmp(encoding_type,"RAW"))==0) 
#endif
						{
							fp=fopen(filename,"w");
							if(fp!=NULL)
							{
								fwrite(mysqlRow[(num_fields-1)],sizeof(char),(lengths[(num_fields-1)]),fp); 
							} else {
								prterr("Error:  Cannot open file [%s] for writing.",filename);
							}
							if(fp!=NULL) fclose(fp); 
#ifdef WIN32
						}else if((stricmp(encoding_type,"BASE64_DECODE"))==0) {
#else
						}else if((strcasecmp(encoding_type,"BASE64_DECODE"))==0) {
#endif
							decode_base64_to_file(filename,mysqlRow[(num_fields-1)]);
						}else{
							fp=fopen(filename,"w");
							if(fp!=NULL)
							{
								fwrite(mysqlRow[(num_fields-1)],sizeof(char),(lengths[(num_fields-1)]),fp); 
							} else {
								prterr("Error:  Cannot open file [%s] for writing.",filename);
							}
							if(fp!=NULL) fclose(fp); 
						}

					}
				}
				mysql_free_result(mysqlResult);
			} else {
				mysql_free_result(mysqlResult);
				prterr("Error: No results found in table %s.\n",db_file);
			}
		}else {
			prterr("Error:  Query Failed.\nQuery:  [%s].\n",temp);
		}

		if(temp!=NULL) Rfree(temp);
			
	} else {
		prterr("Error:  MySQL Server Connection Lost!");
	}
	mysql_close(mysql);
	mysql_library_end();
	freeapplib(sql_fields);
	freeapplib(sql_values);
	return (err);
#else
	return(-1);
#endif
}
Exemple #13
0
/*
 * 子线程:用于定时给所有已连接设备发送广告信息
 *         仅在第一个连接建立时启动,
 * TODO: 包裹数据库函数,优化查询循环
 */
static void *pthr_adver_boardcast(void *arg)
{
    pthread_detach(pthread_self());
    int          connfd;
    char sendbuf[BUFFSIZE];

    MYSQL       *db_mysql;
    MYSQL_RES   *db_result;
    MYSQL_ROW    db_row;
    MYSQL_FIELD *db_field;

    unsigned int timeout = 3000;    /* mysqlopt timeout val */
    unsigned int num_fields;        /* fields numbers of query result */
    unsigned int i;                 /* int for loop */
    const char *pQuery_init = "SET NAMES UTF8";     /* set mysql for utf8 */
    const char *pQuery      = "SELECT * FROM `adverinfo`";  /* select table of advertise info */

    /* database init */
    mysql_thread_init();
    if ( NULL == (db_mysql = mysql_init(NULL))) {
        printf("mysql init error\n");
        return(NULL);
    }
    
//    mysql_options(db_mysql, MYSQL_OPT_CONNECT_TIMEOUT, &timeout);

    if (!mysql_real_connect(db_mysql, DBHOST, DBUSER, DBPWD, 
                        DBNAME, 0, NULL, 0))
        handle_mysql_error("connect failed: %s\n", db_mysql);
    /* set mysql names for UTF8 */
    if (0 != mysql_real_query(db_mysql, pQuery_init, strlen(pQuery_init)))
        handle_mysql_error("utf8 init failded: %s\n", db_mysql);

    while(1) {  /* get adverinfo for loop */
        if (0 != mysql_real_query(db_mysql, pQuery, strlen(pQuery)))
            handle_mysql_error("query for adverinfo error: %s\n", db_mysql);
    
        if ( NULL == (db_result = mysql_store_result(db_mysql)))
            handle_mysql_error("fetch result failed: %s\n", db_mysql);

        while (NULL != (db_row = mysql_fetch_row(db_result)))
        {
            memset(sendbuf, 0, sizeof(sendbuf));
            sprintf(sendbuf, "Adver: %s\n", db_row[1]);
            for (i = 0; i <= maxi; i++)
            {
                connfd = client[i];    
                send(connfd, sendbuf, sizeof(sendbuf), 0);
            }
            sleep(2);
        }
        free(db_row);

        mysql_free_result(db_result);
    }
    mysql_close(db_mysql);
    
    mysql_thread_end();
    mysql_library_end();

    return(NULL);
}
Exemple #14
0
void serve(int listenfd)
{
    int             i, connfd, sockfd;
    int             maxfd, nready;
    ssize_t         n;
    pthread_t       tid;
    socklen_t       alen, blen;
    struct  addrinfo cliaddr;
    fd_set  rset, allset;
    char    buf[MAXLINE];
    char    clihost[BUFLEN];
    char    cliserv[BUFLEN];
    const char *query_init = "SET NAMES UTF8";

    MYSQL   *db_insert;
    
    maxfd = listenfd;

    mysql_library_init(0, NULL, NULL);

    if ( NULL == (db_insert = mysql_init(NULL))) {
        printf("mysql init error\n");
        exit(1);
    }

    if (!mysql_real_connect(db_insert, DBHOST, DBUSER, DBPWD, 
                        DBNAME, 0, NULL, 0))
        handle_mysql_error("connect failed: %s\n", db_insert);
    /* set mysql names for UTF8 */
    if (0 != mysql_real_query(db_insert, query_init, strlen(query_init)))
        handle_mysql_error("utf8 init failded: %s\n", db_insert);

    for (i = 0; i < FD_SETSIZE; i++)
        client[i] = -1;

    FD_ZERO(&allset);
    FD_SET(listenfd, &allset);

    for ( ; ; ) 
    {
        rset = allset;
        nready = select(maxfd+1, &rset, NULL, NULL, NULL);

        if (FD_ISSET(listenfd, &rset)) {    /* new connection */
            alen = sizeof(cliaddr);
            memset(&cliaddr, 0, alen);
            if ((connfd = accept(listenfd, (SA *)&cliaddr, &alen)) < 0) {
                syslog(LOG_ERR, "serv: accept error: %s", strerror(errno));
                exit(1);
            }

            for (i = 0; i < FD_SETSIZE; i++)
                if (client[i] < 0) {
                    client[i] = connfd;     /* save descriptor */
                    break;
                }

            if (i == FD_SETSIZE)
                handle_error("too many clients");

            FD_SET(connfd, &allset);        /* add new fd to set */
            
            if (connfd > maxfd)
                maxfd = connfd;

            if (i > maxi)
                maxi = i;                   /* max index in client[] */
            if (flag_advpthread) {
                pthread_create(&tid, NULL, pthr_adver_boardcast, NULL);
                flag_advpthread = 0;
            }

            if (--nready <= 0)              /* if there is only one fd return in select */
                continue;
        }

        for (i = 0; i <= maxi; i++) {       /* check all clients for data */
            if ( (sockfd = client[i]) < 0)
                continue;

            if (FD_ISSET(sockfd, &rset)) {
                if ((n = read(sockfd, buf, MAXLINE)) == 0) {
                    /* Connection closed by client */
                    close(sockfd);
                    FD_CLR(sockfd, &allset);
                    client[i] = -1;
                } else
                    date_insert(buf, db_insert);
                    //write(STDOUT_FILENO, buf, n);

                if (--nready <= 0)
                    break;
            }
        }
    }

    mysql_close(db_insert);
    mysql_library_end();
}
Exemple #15
0
				~Library () noexcept {
				
					if (success) mysql_library_end();
				
				}
Exemple #16
0
void Database::CleanupLibs()
{
	mysql_library_end();
}
Exemple #17
0
int
main (int argc, char *argv[])
{
int        opt_err;
MYSQL      *conn;   /* pointer to connection handler */
MYSQL_STMT *stmt;   /* pointer to statement handler */

  MY_INIT (argv[0]);
  load_defaults ("my", client_groups, &argc, &argv);

  if ((opt_err = handle_options (&argc, &argv, my_opts, get_one_option)))
    exit (opt_err);

  /* solicit password if necessary */
  if (ask_password)
    opt_password = get_tty_password (NULL);

  /* get database name if present on command line */
  if (argc > 0)
  {
    opt_db_name = argv[0];
    --argc; ++argv;
  }

  /* initialize client library */
  if (mysql_library_init (0, NULL, NULL))
  {
    print_error (NULL, "mysql_library_init() failed");
    exit (1);
  }

  /* initialize connection handler */
  conn = mysql_init (NULL);
  if (conn == NULL)
  {
    print_error (NULL, "mysql_init() failed (probably out of memory)");
    exit (1);
  }

#ifdef HAVE_OPENSSL
  /* pass SSL information to client library */
  if (opt_use_ssl)
    mysql_ssl_set (conn, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
                   opt_ssl_capath, opt_ssl_cipher);
  mysql_options (conn,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                 (char*)&opt_ssl_verify_server_cert);
#endif

  /* connect to server */
  if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
      opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
  {
    print_error (conn, "mysql_real_connect() failed");
    mysql_close (conn);
    exit (1);
  }

/* #@ _VERIFY_SERVER_VERSION_ */
  if (mysql_get_server_version (conn) < 50503)
  {
    print_error (NULL, "Prepared CALL requires MySQL 5.5.3 or higher");
    mysql_close (conn);
    exit (1);
  }
/* #@ _VERIFY_SERVER_VERSION_ */

  /* initialize statement handler, execute prepared CALL, close handler */
/* #@ _CALL_PROCEDURE_ */
  stmt = mysql_stmt_init (conn);
  if (!stmt)
    print_error (NULL, "Could not initialize statement handler");
  else
  {
    if (exec_prepared_call (stmt) == 0)
      process_call_result (conn, stmt);
    mysql_stmt_close (stmt);
  }
/* #@ _CALL_PROCEDURE_ */

  /* disconnect from server, terminate client library */
  mysql_close (conn);
  mysql_library_end ();
  exit (0);
}
Exemple #18
0
int main(int argc, char *argv[])
{
	MYSQL *connection;
	my_bool reconnect = true;
	char clientid[24];
	struct mosquitto *mosq;
	int rc = 0;

	signal(SIGINT, handle_signal);
	signal(SIGTERM, handle_signal);

	mysql_library_init(0, NULL, NULL);
	mosquitto_lib_init();

	connection = mysql_init(NULL);

	if(connection){
		mysql_options(connection, MYSQL_OPT_RECONNECT, &reconnect);

		connection = mysql_real_connect(connection, db_host, db_username, db_password, db_database, db_port, NULL, 0);

		if(connection){
			stmt = mysql_stmt_init(connection);

			mysql_stmt_prepare(stmt, db_query, strlen(db_query));

			memset(clientid, 0, 24);
			snprintf(clientid, 23, "mysql_log_%d", getpid());
			mosq = mosquitto_new(clientid, true, connection);
			if(mosq){
				mosquitto_connect_callback_set(mosq, connect_callback);
				mosquitto_message_callback_set(mosq, message_callback);


			    rc = mosquitto_connect(mosq, mqtt_host, mqtt_port, 60);

				mosquitto_subscribe(mosq, NULL, "nodes/01/#", 0);

				while(run){
					rc = mosquitto_loop(mosq, -1, 1);
					if(run && rc){
						sleep(20);
						mosquitto_reconnect(mosq);
					}
				}
				mosquitto_destroy(mosq);
			}
			mysql_stmt_close(stmt);

			mysql_close(connection);
		}else{
			fprintf(stderr, "Error: Unable to connect to database.\n");
			printf("%s\n", mysql_error(connection));
			rc = 1;
		}
	}else{
		fprintf(stderr, "Error: Unable to start mysql.\n");
		rc = 1;
	}

	mysql_library_end();
	mosquitto_lib_cleanup();

	return rc;
}
Exemple #19
0
void Connector::unregisterConnector()
{
	Poco::Data::SessionFactory::instance().remove(KEY);
	mysql_library_end();
}
Exemple #20
0
int main(int argc, char** argv)
{
  int channel = 1, status = AMQP_STATUS_OK, cnfnlen;
  amqp_socket_t *socket = NULL;
  amqp_connection_state_t conn;
  amqp_rpc_reply_t ret;
  amqp_message_t *reply = NULL;
  amqp_frame_t frame;
  struct timeval timeout;
  MYSQL db_inst;
  char ch, *cnfname = NULL, *cnfpath = NULL;
  static const char* fname = "consumer.cnf";

  if((c_inst = calloc(1,sizeof(CONSUMER))) == NULL){
    fprintf(stderr, "Fatal Error: Cannot allocate enough memory.\n");
    return 1;
  }

  if(signal(SIGINT,sighndl) == SIG_IGN){
    signal(SIGINT,SIG_IGN);
  }

  while((ch = getopt(argc,argv,"c:"))!= -1){
    switch(ch){
    case 'c':
      cnfnlen = strlen(optarg);
      cnfpath = strdup(optarg);
      break;
    default:

      break;
    }
  }

  cnfname = calloc(cnfnlen + strlen(fname) + 1,sizeof(char));

  if(cnfpath){

    /**Config file path as argument*/
    strcpy(cnfname,cnfpath);
    if(cnfpath[cnfnlen-1] != '/'){
      strcat(cnfname,"/");
    }

  }  
  
  strcat(cnfname,fname);

  timeout.tv_sec = 1;
  timeout.tv_usec = 0;
  all_ok = 1;
  out_fd = NULL;



  /**Parse the INI file*/
  if(ini_parse(cnfname,handler,NULL) < 0){
    
    /**Try to parse a config in the same directory*/
    if(ini_parse(fname,handler,NULL) < 0){
      fprintf(stderr, "Fatal Error: Error parsing configuration file!\n");
    goto fatal_error;

    }
  }

  if(out_fd == NULL){
    out_fd = stdout;
  }

  fprintf(out_fd,"\n--------------------------------------------------------------\n");
  
  /**Confirm that all parameters were in the configuration file*/
  if(!c_inst->hostname||!c_inst->vhost||!c_inst->user||
     !c_inst->passwd||!c_inst->dbpasswd||!c_inst->queue||
     !c_inst->dbserver||!c_inst->dbname||!c_inst->dbuser){
    fprintf(stderr, "Fatal Error: Inadequate configuration file!\n");
    goto fatal_error;    
  }

  connectToServer(&db_inst);

  if((conn = amqp_new_connection()) == NULL || 
     (socket = amqp_tcp_socket_new(conn)) == NULL){
    fprintf(stderr, "Fatal Error: Cannot create connection object or socket.\n");
    goto fatal_error;
  }
  
  if(amqp_socket_open(socket, c_inst->hostname, c_inst->port)){
    fprintf(stderr, "RabbitMQ Error: Cannot open socket.\n");
    goto error;
  }
  
  ret = amqp_login(conn, c_inst->vhost, 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, c_inst->user, c_inst->passwd);

  if(ret.reply_type != AMQP_RESPONSE_NORMAL){
    fprintf(stderr, "RabbitMQ Error: Cannot login to server.\n");
    goto error;
  }

  amqp_channel_open(conn, channel);
  ret = amqp_get_rpc_reply(conn);

  if(ret.reply_type != AMQP_RESPONSE_NORMAL){
    fprintf(stderr, "RabbitMQ Error: Cannot open channel.\n");
    goto error;
  }  

  reply = malloc(sizeof(amqp_message_t));
  if(!reply){
    fprintf(stderr, "Error: Cannot allocate enough memory.\n");
    goto error;
  }
  amqp_basic_consume(conn,channel,amqp_cstring_bytes(c_inst->queue),amqp_empty_bytes,0,0,0,amqp_empty_table);

  while(all_ok){
     
    status = amqp_simple_wait_frame_noblock(conn,&frame,&timeout);

    /**No frames to read from server, possibly out of messages*/
    if(status == AMQP_STATUS_TIMEOUT){ 
      sleep(timeout.tv_sec);
      continue;
    }

    if(frame.payload.method.id == AMQP_BASIC_DELIVER_METHOD){

      amqp_basic_deliver_t* decoded = (amqp_basic_deliver_t*)frame.payload.method.decoded;
	
      amqp_read_message(conn,channel,reply,0);

      if(sendMessage(&db_inst,reply)){

	fprintf(stderr,"RabbitMQ Error: Received malformed message.\n");
	amqp_basic_reject(conn,channel,decoded->delivery_tag,0);	
	amqp_destroy_message(reply);

      }else{

	amqp_basic_ack(conn,channel,decoded->delivery_tag,0);
	amqp_destroy_message(reply);	

      }
      
    }else{
      fprintf(stderr,"RabbitMQ Error: Received method from server: %s\n",amqp_method_name(frame.payload.method.id));
      all_ok = 0;
      goto error;
    }

  }

  fprintf(out_fd,"Shutting down...\n");
 error:

  mysql_close(&db_inst);
  mysql_library_end();
  if(c_inst && c_inst->query_stack){

    while(c_inst->query_stack){
      DELIVERY* d = c_inst->query_stack->next;
      amqp_destroy_message(c_inst->query_stack->message);
      free(c_inst->query_stack);
      c_inst->query_stack = d;
    }

  }
  
  amqp_channel_close(conn, channel, AMQP_REPLY_SUCCESS);
  amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
  amqp_destroy_connection(conn);
 fatal_error:

  if(out_fd){
    fclose(out_fd);
  }

  
  if(c_inst){

    free(c_inst->hostname);
    free(c_inst->vhost);
    free(c_inst->user);
    free(c_inst->passwd);
    free(c_inst->queue);
    free(c_inst->dbserver);
    free(c_inst->dbname);
    free(c_inst->dbuser);
    free(c_inst->dbpasswd);    
    free(c_inst);
    
  }

  
  
  return all_ok;
}
Exemple #21
0
static void
dblayer_finalize(void) {
#ifdef HAVE_MYSQL
    mysql_library_end();
#endif
}
Exemple #22
0
void Connector::unregisterConnector()
{
	Poco::Data::SessionFactory::instance().remove(POCO_DATA_MYSQL_CONNECTOR_NAME);
	mysql_library_end();
}
Exemple #23
0
/* Class method: MySQL client library finalization */
void MysqlConnection_onstop(void) {
        if (mysql_get_client_version() >= 50003)
                mysql_library_end();
        else
                mysql_server_end();
}
Exemple #24
0
int
main (int argc, char *argv[])
{
int opt_err;

  MY_INIT (argv[0]);
  load_defaults ("my", client_groups, &argc, &argv);

  if ((opt_err = handle_options (&argc, &argv, my_opts, get_one_option)))
    exit (opt_err);

  /* solicit password if necessary */
  if (ask_password)
    opt_password = get_tty_password (NULL);

  /* get database name if present on command line */
  if (argc > 0)
  {
    opt_db_name = argv[0];
    --argc; ++argv;
  }

  /* initialize client library */
  if (mysql_library_init (0, NULL, NULL))
  {
    print_error (NULL, "mysql_library_init() failed");
    exit (1);
  }

/* #@ _SET_UP_SSL_ */
  /* initialize connection handler */
  conn = mysql_init (NULL);
  if (conn == NULL)
  {
    print_error (NULL, "mysql_init() failed (probably out of memory)");
    exit (1);
  }

#ifdef HAVE_OPENSSL
  /* pass SSL information to client library */
  if (opt_use_ssl)
    mysql_ssl_set (conn, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
                   opt_ssl_capath, opt_ssl_cipher);
  mysql_options (conn,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                 (char*)&opt_ssl_verify_server_cert);
#endif

  /* connect to server */
  if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
      opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
  {
    print_error (conn, "mysql_real_connect() failed");
    mysql_close (conn);
    exit (1);
  }
/* #@ _SET_UP_SSL_ */

  printf ("Testing connection...\n");
  process_statement (conn, "SHOW STATUS LIKE 'Ssl_cipher'");
  printf ("If Ssl_cipher is non-blank, the connection is secure.\n");

  while (1)
  {
    char  buf[10000];

    fprintf (stderr, "query> ");                  /* print prompt */
    if (fgets (buf, sizeof (buf), stdin) == NULL) /* read statement */
      break;
    if (strcmp (buf, "quit\n") == 0 || strcmp (buf, "\\q\n") == 0)
      break;
    process_statement (conn, buf);                /* execute it */
  }

  /* disconnect from server, terminate client library */
  mysql_close (conn);
  mysql_library_end ();
  exit (0);
}
Exemple #25
0
void MySQL::Library_End()
{
    mysql_library_end();
}
Exemple #26
0
int main (int argc, char *argv[])
{
	payguide::time_start=time(NULL);
	int Ppid=CheckIfPayguideAlreadyUp();
	if (Ppid==0)
	{
		if (MakeLockFile()!=0)
		{
			std::cout << "Error while creating lock file. Can't write /tmp/payguide.lock" << std::endl;
			LogWrite(LOGMSG_CRITICAL, "Error while creating lock file. Can't write /tmp/payguide.lock");
		}
	}
	else
	{
		
		char msg[512];
		snprintf(msg, 511,"Error: payguide already running as process %i. Balling out.", Ppid);
		std::cout << msg << std::endl;
		LogWrite(LOGMSG_CRITICAL, msg);
		exit(0);
	}
	
	PayguideInit();
	WorkInit();
	bool work_init_already=true;
	
	bonbon::BonbonInit();
	
	
	PerlInit(argv[0], payguide::perl_module.c_str());
	payguide::data_conventor.Init();
	for (EVER)
	{
		std::cout << "Running xml paycheck..." << std::endl;
	        const char *main_config_file="/etc/payguide.cfg";
	        paycheck::CPaycheckCore paycheck_core;
	        paycheck_core.LoadConfig(main_config_file);
	        paycheck::CServer server_code;
	        bonbon::CJobManager in_manager;
	        std::vector <paycheck::CSocket *> connections_store;
	        paycheck::CPaycheckThreadParam params(&in_manager, &connections_store, &paycheck_core);
	        bonbon::CThread xml_server1(server_code, params);
	        payguide::xml_paycheck_core=&paycheck_core;

		payguide::quit=false;
		if (!work_init_already)
			WorkInit();
		int sleep_count=0;
		timespec req;
		req.tv_sec=0;
		req.tv_nsec=50000000;
		
		
		payguide::working=true;
		
		LogWrite(LOGMSG_SYSTEM, "Payguide server started sucessful and ready for a work");
		
		/* Ok, lets rock */
		
		SPay *new_pay=NULL;
		sem_wait(&payguide::shutdown_lock);
		bool working_state=payguide::working;
		sem_post(&payguide::shutdown_lock);
		
		printf("TESTING printf(): if you see that in log - world gone mad\n");
		std::cout << "TESTING std::cout: if you see that in log - world gone mad" << std::endl;
		
		while (working_state)
		{
			sem_wait(&payguide::shutdown_lock);
			working_state=payguide::working;
			sem_post(&payguide::shutdown_lock);

			/* Get next pay from DB */
			if (new_pay==NULL)
			{
				new_pay=paycheck_core.XMLGetNextPay();
				if (new_pay==NULL)
				{
					new_pay=PCGetNextPay();
				
					if (new_pay==NULL)
					{
						//printf("get new pay from DB\n");
						if (sleep_count==1)
							new_pay=DBGetNextPay();
					}
					else if (new_pay->test==NO_TEST)
					{
						LogWrite(LOGMSG_CRITICAL, "Payguide received from BIN PAYCHECK (payd) must be marked as testing. Shutdown.");
						char tmp[1024];
						snprintf(tmp, 1024, "Pay params: id/session=[%lli] terminal=[%lli] operator=%i", new_pay->id, new_pay->terminal_id, new_pay->provider_id); 
						LogWrite(LOGMSG_CRITICAL, tmp);
						exit(-1);
					}
				}
				else if (new_pay->test==NO_TEST)
				{
					LogWrite(LOGMSG_CRITICAL, "Payguide received from XML PAYCHECK must be marked as testing. Shutdown.");
					char tmp[1024];
					snprintf(tmp, 1024, "Pay params: id/session=[%lli] terminal=[%lli] operator=%i", new_pay->id, new_pay->terminal_id, new_pay->provider_id); 
					LogWrite(LOGMSG_CRITICAL, tmp);
					exit(-1);
				}
			}

			if (new_pay!=NULL)
			{
//				char logmsg[101]; snprintf(logmsg, 100,"Working on pay %lli", new_pay->id); SendLogMessages(0, logmsg);
				sem_wait(&payguide::free_workers_lock);
				//printf("lock catched\n");
				/* If were is no free worker - find one or create new. */
				if (payguide::free_worker==NULL)
					SetFreeWorker(NULL);
				
				/* If it's ok - init free worker with a new pay */
				if (payguide::free_worker!=NULL)
				{
					LaunchNewPay(new_pay);
					new_pay=NULL;
					sem_post(&payguide::free_workers_lock);	
				}
				
				/* We can't create a new worker - threads limit hit. */
				else
				{
					//LogWrite(LOGMSG_WARNING, "Threads limit hit. Payguide server is overloaded.");
					sem_post(&payguide::free_workers_lock);
					
					if (sleep_count==20)
					{
						ReloadConfigIfImportant();
						ManagerEx();
						sleep_count=0;
						
					}

					nanosleep(&req, NULL);sleep_count++;
					StatisticTick(0.2);

					
				}
			}
			
			/* No new pays, sleep (nojobs_sleep_time) sec*/
			else
			{
				
				/* Manage inactive workers */
				if (sleep_count==20)
				{
					ReloadConfigIfImportant();
					ManagerEx();
					sleep_count=0;
				}
//				sleep(SLEEP_TIME); sleep_count=20;
				nanosleep(&req, NULL);sleep_count++;
				StatisticTick(0.2);

			}
		}
		
		/* Waiting for all workers, or even cancel all pays if force_quit is 1 ... */
		LogWrite(LOGMSG_SYSTEM, "Waiting for all active pays to end - for safe exit - you had to specify right timeouts in your modules.");
		WaitForAllPaysToFinish(force_quit);
		
		/* If it's not reboot - exit */
		sem_wait(&payguide::shutdown_lock);
		bool quit_state=payguide::quit;
		sem_post(&payguide::shutdown_lock);
		if (quit_state)
		{
			LogWrite(LOGMSG_SYSTEM, "Payguide server shutdown normally.");
			LogWrite(LOGMSG_SYSTEM, "Bye-bye!");
			
			/* Stop connection with MySQL database */
			DBShutdown();
		
			/* Stop control server. */
			//CtlServerStop();
			
			mysql_library_end();
			
			if (ossl_lock!=NULL)
				delete [] ossl_lock;
			if (pc_init_result==0)
				PCShutdown();
			/* CleanUp will be automatically called by atexit() function */
			if (RemoveLockFile()!=0)
			{
				std::cout << "Can't remove /tmp/payguide.lock. File doesn't exist or maybe you should delete it manually."  << std::endl;
				LogWrite(LOGMSG_CRITICAL, "Can't remove /tmp/payguide.lock. File doesn't exist or maybe you should delete it manually.");
			}
			OperatorsShutdown();
			EVP_cleanup();
			payguide::data_conventor.Clean();
			PerlShutdown();
			printf("destroying queue\n");
			in_manager.Destroy();
			printf("done\n");
			exit (0);
		}
		
		/* Stop connection with MySQL database */
		DBShutdown();
		
		printf("destroying queue\n");
		in_manager.Destroy();
		printf("done\n");
	        server_code.Kill();
		LogWrite(LOGMSG_SYSTEM, "Rebooting...");
		work_init_already=false;
		CleanUp();
	}
	return 0;
}
void Database::CleanupLibs()
{
#if defined(ENABLE_DATABASE_MYSQL)
		mysql_library_end();
#endif
}
Exemple #28
0
int main(int argc,char *argv[])
{
	MYSQL *mysql;
	MYSQL_RES *results = NULL;
	MYSQL_ROW row;
	char	sql[1024];
	MYSQL_TIME	ts;
	MYSQL_BIND	bind[4];
	MYSQL_STMT	*stmt;

	//初始化数据库
	mysql = mysql_init(NULL);

	//开始数据库连接
	if(!(mysql_real_connect(mysql,"localhost","casshern","goodbaby","test",0,NULL,0))){
		printf("mysql connect error!");
		exit(2);
	}

	strcpy(sql,"insert into test_time(time_field,date_field,timestamp_field,datetime_field) values(?,?,?,?)");

	stmt = mysql_stmt_init(mysql);

	if(!stmt){
		perror("mysql_stmt_init error\n");
		exit(0);
	}

	if(mysql_stmt_prepare(stmt,sql,strlen(sql))) {
		perror("mysql_stmt_prepare error\n");
		exit(0);
	}

	bind[0].buffer_type = MYSQL_TYPE_TIME;
	bind[0].buffer = (char *)&ts;
	bind[0].is_null = 0;
	bind[0].length = 0;


	bind[1].buffer_type = MYSQL_TYPE_DATE;
	bind[1].buffer = (char *)&ts;
	bind[1].is_null = 0;
	bind[1].length = 0;

	bind[2].buffer_type = MYSQL_TYPE_TIMESTAMP;
	bind[2].buffer = (char *)&ts;
	bind[2].is_null = 0;
	bind[2].length = 0;

	bind[3].buffer_type = MYSQL_TYPE_DATETIME;
	bind[3].buffer = (char *)&ts;
	bind[3].is_null = 0;
	bind[3].length = 0;


	ts.year = 2002;
	ts.month = 02;
	ts.day = 03;

	ts.hour=23;
	ts.minute = 45;
	ts.second = 20;

	if(mysql_stmt_bind_param(stmt,bind)){
		perror("mysql_stmt_bind_param error!\n");
		exit(0);
	}

	if(mysql_stmt_execute(stmt)) {
		perror("mysql_stmt_execute error!\n");
		exit(0);
	}

	mysql_stmt_close(stmt);
	//关闭数据库连接
	mysql_close(mysql);

	//释放数据库内容
	mysql_library_end();
	return 0;
}
Exemple #29
0
/*==============================================================================
------------------------------------------------------------------------------*/
void db_close(
    )
{
    mysql_library_end();
}
int main (int argc, char *argv[])
{


    trace(argc, argv);

    int opt_err;

    MY_INIT (argv[0]);
    load_defaults ("my", client_groups, &argc, &argv);

    if ((opt_err = handle_options (&argc, &argv, my_opts, get_one_option)))
        exit (opt_err);

    /* solicit password if necessary */
    if (ask_password)
        opt_password = get_tty_password (NULL);

    /* get database name if present on command line */
    if (argc > 0)
    {
        opt_db_name = argv[0];
        --argc;
        ++argv;
    }

    /* initialize client library */
    if (mysql_library_init (0, NULL, NULL))
    {
        print_error (NULL, "mysql_library_init() failed");
        exit (1);
    }

    /* initialize connection handler */
    conn = mysql_init (NULL);
    if (conn == NULL)
    {
        print_error (NULL, "mysql_init() failed (probably out of memory)");
        exit (1);
    }

#ifdef HAVE_OPENSSL
    /* pass SSL information to client library */
    if (opt_use_ssl)
        mysql_ssl_set (conn, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
                       opt_ssl_capath, opt_ssl_cipher);
#if (MYSQL_VERSION_ID >= 50023 && MYSQL_VERSION_ID < 50100) \
    || MYSQL_VERSION_ID >= 50111
    mysql_options (conn,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                   (char*)&opt_ssl_verify_server_cert);
#endif
#endif

    /* connect to server */
    if (mysql_real_connect (conn, opt_host_name, opt_user_name, opt_password,
                            opt_db_name, opt_port_num, opt_socket_name, opt_flags) == NULL)
    {
        print_error (conn, "mysql_real_connect() failed");
        mysql_close (conn);
        exit (1);
    }

    process_prepared_statements (conn);

    /* disconnect from server, terminate client library */
    mysql_close (conn);
    mysql_library_end ();
    exit (0);
}