Friday, June 22, 2007

Count occurence of character (i.e. line breaks) in a MySQL field

Unfortunately, there is no inbuilt MySQL function to count the occurance of a character in string. By counting the number of characters in the original string, then temporarily 'deleting' the character you want to count and counting the string again, subtracting the first count from the second, you get the number of occurances:

SELECT LENGTH('foobarfoobarfoobar') - LENGTH(REPLACE('foobarfoobarfoobar', 'b', '')) AS `occurances`
--> 3

Obviously, in this example 'b' is the string you want to count the number of occurances of.

You can use the same principle to count the number of lines in a field, by adding one to the difference:

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;
}
}