Thursday, June 21, 2007

Connecting C / C++ with MYSQL

This code help you to create a connection with C/C++ and MYSQL

Create a header " .h" file and write these steps in that file

#include "/usr/include/mysql/mysql.h"
#include
using namespace std;

MYSQL mysql;
MYSQL_RES *Result;
MYSQL_ROW FirstTblRow, SecTblRow, ThrdTblRow, TblField ;

int C_Connect_MYSQL( char *hostname, char *username, char *passwd, char *dbname )
{
mysql_init(&mysql);

if(!mysql_real_connect(&mysql, hostname, username, passwd, dbname, 0, NULL, 0))
{
printf("%d: %s \n", mysql_errno(&mysql), mysql_error(&mysql));
printf("Connection Refused by MYSQL\n");
return 1;
}
else{
printf("Connection OK by MYSQL\n");
return 0;
}
}

MYSQL_RES * Exectue_Query ( char *Exec_Qry )
{

if(mysql_query(&mysql, Exec_Qry)) {
cout << Exec_Qry << endl;
cout << "Error in Query!"< }
else {
Result = mysql_store_result(&mysql);
}
return Result;
}


MYSQL_RES * MySqlListField ( char *TableName )
{
Result = mysql_list_fields ( &mysql, TableName, NULL );
return Result;
}



After this create the ".c" file and write the following steps in main() function

char *Qry[] = "select * from YOUR_TABLE_NAME;";

int ret = C_Connect_MYSQL( MY_HOSTNAME, MY_USERNAME, MY_PASSWORD, MY_DATABASE);

if ( ret == 1 ) exit(0);

FirstTableName = Exectue_Query( Qry );

if ( mysql_num_rows(FirstTableName) > 0 ) {

while( (FirstTblRow = mysql_fetch_row( FirstTableName )))
{
cout << TblField[1] ? TblField[1] : "NULL" << endl;
}
}

No comments: