Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing MYSQL results

Status
Not open for further replies.

DMAN3021

Programmer
Aug 20, 2002
40
CA
I'm working on a C program that uses MYSQL to access and modify a database. Right now, I am trying to run a SELECT query on the database, and to populate a list with the results.

The thing is, in all the examples I can find, the MYSQL_RES structure is processed locally. I on the other hand, want an outside function to call my run_query() function, and then process the result set itself.

The problem I get is that the MYSQL_RES I receive from my query function is not good. Even when I debug, I can see that I have a correct result set, up until I exit my query function and return to my list function.

Anyone have an example of how to correctly pass a MYSQL_RES structure from one function to another?

Heres my code:

in connect.c
Code:
/* Run a query */
int run_query(char *query, MYSQL_RES *res_set) {
  
	if (open_connection() != 1) {
		/* could not connect to MySQL */
		print_error(&connection, "Unable to connect to MySQL");
		return 0;
		
	} else {
		if (mysql_query(&connection, query) != 0) {
			/* Query has failed */
			print_error(&connection, "Query FAILED!\n");
			close_connection();
			return 0;
			
		} else {
			/* Query has passed, process results */
			res_set = mysql_store_result(&connection);
			
			if (res_set) {
				/* If a result set was returned */
				process_result_set(res_set);
				mysql_free_result(res_set);
			} else {
				/* No result was returned */
				if (mysql_field_count(&connection) == 0) {
					printf("%lu rows affected\n", (unsigned long) mysql_affected_rows(&connection));				
				} else { /* an error occured */
					print_error(&connection, "Could not retrieve the result set");
				}
			}
		}
		
		close_connection();
	}	
	return 1;
}


in list.c
Code:
int
ListTGs( )

	{
	MYSQL_RES *res_set;
	MYSQL_ROW	row;
	MYSQL_FIELD	*field;
	char *query = "SELECT * FROM THETABLE";
	int i;

	/* Get the list */
	run_query_result(query, res_set);
	
	/*Lets try some stuff with res_set */
	mysql_field_seek(&res_set, 0);
	for (i=0; i<mysql_num_fields(&res_set); i++) {
		field = mysql_fetch_field(&res_set);
		if (row[i] == NULL) {
			printf("NULL\t");
		} else {
			printf("%s\t", row[i]);
		}
	}
	
	return( Pt_CONTINUE );
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top