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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple program to query mysql 1

Status
Not open for further replies.

shadedecho

Programmer
Oct 4, 2002
336
US
I want to write a simple c/c++ program that does some specific, sensitive querying of a local mysql database.

i know there are probably a million ways to do this... but i don't need any kind of special ability, just some simple select and insert queries... and no need for advanced exception handling or anything like that.

basically, i don't really know the simple way to make some queries from inside a c/c++ program. I have the "libmysqlclient" installed on this box, and was hoping I could utilize that, but i don't how to go about this. also, i looked into the "mysql++" api library from the folks at mysql. but i can't seem to get it to install properly.

can anyone point me in the right direction?
 
We have a perl module connect to the mysql db, and are trying to call it from C++, and have record(s) returned. Still working on the C++ part.
 
I have used the mysql.h and the included functions without much problem. This is a pretty easy way to use mysql from c++. Here are some examples.

Include Statement:
Code:
#include "/usr/include/mysql/mysql.h"

Declarations:
Code:
	MYSQL mysql;
	MYSQL_RES *result;
	MYSQL_ROW row;

Initialize and connect to the database
Code:
	if (!mysql_init(&mysql))
	{
		fprintf(stderr, "%d: %s \n", mysql_errno(&mysql), mysql_error(&mysql));
		exit(1);
	}
	
	if(!mysql_real_connect(&mysql, "localhost", "user", "pass", "db_name", 0, NULL, 0))
	{
		fprintf(stderr, "%d: %s\n", mysql_errno(&mysql), mysql_error(&mysql));
		exit(1);
	}

Select Statement
Code:
	sql_string = "select * from tbl_name group by acct_nbr";
	if (mysql_query(&mysql, sql_string.c_str()))
	{
		fprintf(stderr, "%d: %s \n", mysql_errno(&mysql), mysql_error(&mysql));
		return(-1);
	}
	
	result = mysql_store_result(&mysql);	
	while (row=mysql_fetch_row(result))
	{
		total += atof(row[PRICE]);					// execute the command
		if (mysql_query(&mysql, buf))
		{
			fprintf(stderr, "%d: %s \n", mysql_errno(&mysql), mysql_error(&mysql));
		}
	}
	mysql_free_result(result);
I normally declare an enum to set up the fields in the table so that I can reference them by name instead of position. Otherwise, treat the rows like any normal array in C.

Hope this helps.

- flub
 
its a long time removed, but this answer finally helped me get on the right track for my project! it's working great now, after several days solid work. :) thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top