473,387 Members | 1,700 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Reg: Extracting the data to CSV format

Hello Everyone

A quick and direct question: I need a C/C++ program to extract the data from the database and the output should be in CSV "Comma Separated Value" format.
Briefly: I will be given a database and my work is to extract a particular data from that whole database and should get a output in CSV format. The database given to me has 24 tables and I need to extract data from any one of the table and if I press the run button I should get the output directly in CSV format.
Program what I have: The program what I have is just to get the details of each table---
Expand|Select|Wrap|Line Numbers
  1. #include        <windows.h>
  2. #include    <stdio.h>
  3. #include    <string.h>
  4.  
  5. #include    <mysql.h>
  6.  
  7. #define        DEFALT_SQL_STMT    "SELECT * FROM db"
  8. #ifndef offsetof
  9. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
  10. #endif
  11.  
  12. int
  13. main( int argc, char * argv[] )
  14. {
  15.  
  16.   char        szSQL[ 200 ], aszFlds[ 25 ][ 25 ], szDB[ 50 ] ;
  17.   const  char   *pszT;
  18.   int            i, j, k, l, x ;
  19.   MYSQL        * myData ;
  20.   MYSQL_RES    * res ;
  21.   MYSQL_FIELD    * fd ;
  22.   MYSQL_ROW    row ;
  23.  
  24.   //....just curious....
  25.   printf( "sizeof( MYSQL ) == %d\n", sizeof( MYSQL) ) ;
  26.   if ( argc == 2 )
  27.     {
  28.       strcpy( szDB, argv[ 1 ] ) ;
  29.       strcpy( szSQL, DEFALT_SQL_STMT ) ;
  30.       if (!strcmp(szDB,"--debug"))
  31.       {
  32.     strcpy( szDB, "mysql" ) ;
  33.     printf("Some mysql struct information (size and offset):\n");
  34.     printf("net:\t%3d %3d\n",sizeof(myData->net),offsetof(MYSQL,net));
  35.     printf("host:\t%3d %3d\n",sizeof(myData->host),offsetof(MYSQL,host));
  36.     printf("port:\t%3d %3d\n",sizeof(myData->port),offsetof(MYSQL,port));
  37.     printf("protocol_version:\t%3d %3d\n",sizeof(myData->protocol_version),
  38.            offsetof(MYSQL,protocol_version));
  39.     printf("thread_id:\t%3d %3d\n",sizeof(myData->thread_id),
  40.            offsetof(MYSQL,thread_id));
  41.     printf("affected_rows:\t%3d %3d\n",sizeof(myData->affected_rows),
  42.            offsetof(MYSQL,affected_rows));
  43.     printf("packet_length:\t%3d %3d\n",sizeof(myData->packet_length),
  44.            offsetof(MYSQL,packet_length));
  45.     printf("status:\t%3d %3d\n",sizeof(myData->status),
  46.            offsetof(MYSQL,status));
  47.     printf("fields:\t%3d %3d\n",sizeof(myData->fields),
  48.            offsetof(MYSQL,fields));
  49.     printf("field_alloc:\t%3d %3d\n",sizeof(myData->field_alloc),
  50.            offsetof(MYSQL,field_alloc));
  51.     printf("free_me:\t%3d %3d\n",sizeof(myData->free_me),
  52.            offsetof(MYSQL,free_me));
  53.     printf("options:\t%3d %3d\n",sizeof(myData->options),
  54.            offsetof(MYSQL,options));
  55.     puts("");
  56.       }
  57.     }        
  58.   else if ( argc > 2 ) {
  59.     strcpy( szDB, argv[ 1 ] ) ;
  60.     strcpy( szSQL, argv[ 2 ] ) ;
  61.   }
  62.   else {
  63.     strcpy( szDB, "winutms_rt_db" ) ;
  64.     strcpy( szSQL, DEFALT_SQL_STMT ) ;
  65.   }
  66.   //....
  67.  
  68.   if ( (myData = mysql_init((MYSQL*) 0)) && 
  69.        mysql_real_connect( myData, NULL, NULL, NULL, NULL, MYSQL_PORT,
  70.                NULL, 0 ) )
  71.     {
  72.       if ( mysql_select_db( myData, szDB ) < 0 ) {
  73.     printf( "Can't select the %s database !\n", szDB ) ;
  74.     mysql_close( myData ) ;
  75.     return 2 ;
  76.       }
  77.     }
  78.   else {
  79.     printf( "Can't connect to the mysql server on port %d !\n",
  80.         MYSQL_PORT ) ;
  81.     mysql_close( myData ) ;
  82.     return 1 ;
  83.   }
  84.   //....
  85.   if ( ! mysql_query( myData, szSQL ) ) {
  86.     res = mysql_store_result( myData ) ;
  87.     i = (int) mysql_num_rows( res ) ; l = 1 ;
  88.     printf( "Query:  %s\nNumber of records found:  %ld\n", szSQL, i ) ;
  89.     //....we can get the field-specific characteristics here....
  90.     for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
  91.       strcpy( aszFlds[ x ], fd->name ) ;
  92.     //....
  93.     while ( row = mysql_fetch_row( res ) ) {
  94.       j = mysql_num_fields( res ) ;
  95.       printf( "Record #%ld:-\n", l++ ) ;
  96.       for ( k = 0 ; k < j ; k++ )
  97.     printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
  98.         (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
  99.       puts( "==============================\n" ) ;
  100.     }
  101.     mysql_free_result( res ) ;
  102.   }
  103.   else printf( "Couldn't execute %s on the server !\n", szSQL ) ;
  104.   //....
  105.   puts( "====  Diagnostic info  ====" ) ;
  106.   pszT = mysql_get_client_info() ;
  107.   printf( "Client info: %s\n", pszT ) ;
  108.   //....
  109.   pszT = mysql_get_host_info( myData ) ;
  110.   printf( "Host info: %s\n", pszT ) ;
  111.   //....
  112.   pszT = mysql_get_server_info( myData ) ;
  113.   printf( "Server info: %s\n", pszT ) ;
  114.   //....
  115.   res = mysql_list_processes( myData ) ; l = 1 ;
  116.   if (res)
  117.     {
  118.       for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
  119.     strcpy( aszFlds[ x ], fd->name ) ;
  120.       while ( row = mysql_fetch_row( res ) ) {
  121.     j = mysql_num_fields( res ) ;
  122.     printf( "Process #%ld:-\n", l++ ) ;
  123.     for ( k = 0 ; k < j ; k++ )
  124.       printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
  125.           (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
  126.     puts( "==============================\n" ) ;
  127.       }
  128.     }
  129.   else
  130.     {
  131.       printf("Got error %s when retreiving processlist\n",mysql_error(myData));
  132.     }
  133.   //....
  134.   res = mysql_list_tables( myData, "%" ) ; l = 1 ;
  135.   for ( x = 0 ; fd = mysql_fetch_field( res ) ; x++ )
  136.     strcpy( aszFlds[ x ], fd->name ) ;
  137.   while ( row = mysql_fetch_row( res ) ) {    j = mysql_num_fields( res ) ;
  138.     printf( "Table #%ld:-\n", l++ ) ;
  139.     for ( k = 0 ; k < j ; k++ )
  140.       printf( "  Fld #%d (%s): %s\n", k + 1, aszFlds[ k ],
  141.           (((row[k]==NULL)||(!strlen(row[k])))?"NULL":row[k])) ;
  142.     puts( "==============================\n" ) ;
  143. //    int sol;
  144. //  sol= mysql> SELECT absTestID, Messwert, TestID FROM abstest;
  145.   // printf("Resultant value is %d\n",sol);
  146.   }   
  147.   //....
  148.   pszT = mysql_stat( myData ) ;
  149.   puts( pszT ) ;
  150.   //....
  151.   mysql_close( myData ) ;
  152.   return 0 ;
  153.  
  154. }
Kindly help me in this case as soon as possible

Thanks and Regards in advance
Dhanekula. Siva
Nov 3 '08 #1
22 3192
donbock
2,426 Expert 2GB
Do you have a specific question?
... Are you getting a build error?
... Is the program malfunctioning?
Nov 3 '08 #2
Thanks for the reply

The given program is running and even I am getting output for that. but my question is how to extract the data from the above program and the output should be in CSV format.
i.e. If I run the above program the output is the list of processes and tables from mydatabase and I need to extract required data from any of the tables so that if I press the Run button I should directly get CSV output....This is what I need
Nov 4 '08 #3
r035198x
13,262 8TB
Looks like you are using tabs to separate your data? You'd need to change those tabs into commas. Outputting to a file is easy. You can then easily redirect your printf's to print to a file instead using something like
Expand|Select|Wrap|Line Numbers
  1.   FILE *fp;
  2.   if((fp=freopen("file.csv", "w" ,stdout))==NULL) {
  3.     printf("Cannot open file.\n");
  4.     exit(1);
  5.   }
  6.   printf("All printfs should now be printing to the file.");
  7.  
  8. //don't forget somewhere at the end to close the fp  
  9.   fclose(fp);
EDIT: On second thought, why are you doing all this when MySQL has a handy
Expand|Select|Wrap|Line Numbers
  1. SELECT INTO OUTFILE
command
Nov 4 '08 #4
Thank you for the reply

I think you didn't understand my ques may be bcoz of my poor english.

My problem is:: I was given a database with lot of tables in it and my work is to extract some data from any one of the table and I have to analyse the data through MINITAB 15(out of question). I can do it directly in MYSQL front end but, my TL asked me to try it in othér way. i.e. he wants a C/C++ code that extracts the data and get the out put as CSV format. For that I have taken the example program that was given in mysql and changed the database and when I am running it I am just getting the list of the tables. Now my question is how to extract a certain table from that and how to extract the data from that table and how can I get it in .CSV format

Thanks in advance
Siva
Nov 4 '08 #5
r035198x
13,262 8TB
You need to use mysql_query (or mysql_real_query) for the select statement from the tables themselves then use mysql_use_results to process the results. You can about all that from the refmanual itself.
P.S Your English is fine.
Nov 4 '08 #6
Thank you

By using the mentioned commands I am able to extract the data from the table but I am not getting the output in CSV format. Can you provide me any code for doing so in C-lan(I think by using file"fprintf")

Regards
Dhanekula.Siva
Nov 5 '08 #7
r035198x
13,262 8TB
Now read my reply #4 above again.
Nov 5 '08 #8
Hi

ya I have tried with that but I got the following error message

C: \ Program Files \ Microsoft Visual Studio \ MyProject \ winutms \ winutms.cpp (180): error C2664: 'freopen': conversion of the parameter 3 of 'char *' in 'struct _iobuf *' not possible

Can you tell me What is "w" in the given program?
and What is the difference between fopen and freopen?

Thankyou
Nov 6 '08 #9
Banfa
9,065 Expert Mod 8TB
Did you put this

if((fp=freopen("file.csv", "w" ,"stdout"))==NULL) {

instead of this

if((fp=freopen("file.csv", "w" ,stdout))==NULL) {

as post 4 specified?

The "w" instructs the function to create a handle to a writeable file, i.e. an output file not an input file.
Nov 6 '08 #10
Hmmmm again the same error !!!!!
Nov 6 '08 #11
r035198x
13,262 8TB
Let's see the code you used.
P.S Just post the part around which the error is being reported.
Nov 6 '08 #12
FILE *fp;
"""if((fp=freopen("file.csv","w+","row[k]"))== NULL){;"""
printf("cannot open file \n");
exit(1);
}
else printf("All values now printing to the file. \n");
fclose(fp);
}

Near the """quoted """ part
Nov 6 '08 #13
Banfa
9,065 Expert Mod 8TB
if((fp=freopen("file.csv","w+","row[k]"))== NULL){
That is not
if((fp=freopen("file.csv","w+", stdout))== NULL){
as was suggested to you. You can not replace the file pointer stdout with an array of characters "row[k]".

You are clearly calling the function without having taken the trouble to find out what it does, I suggest that you read the function reference.
Nov 6 '08 #14
Ok...But where is my input data.....where can I give that and without giving my input data how can I get the output in CSV format.....
Nov 7 '08 #15
r035198x
13,262 8TB
Read my post number 4 again.
Do you understand the meaning of the word "redirect"?
Nov 7 '08 #16
Sorry....I didn't get you...Can you tell me reg that briefly.....

ThanQ
Nov 7 '08 #17
r035198x
13,262 8TB
Your code already had lots of printfs which were printing to the console. You wanted that output to go to the file instead. That code that I posted redirects the output from going to the console to going to the file. So you just use your printfs after that code but they will be writing to the file rather than writing to the console.
That is the concept of redirecting.
Nov 7 '08 #18
Ok....got it..and even I am getting the output for my program.

Thank you for one and all who help me

C you all in other thread...bye
Nov 7 '08 #19
Hmmmmm again I have a problem with the program.....Now I am able to get a separate .CSV file in my project but the problem is the data what I wana insert into that is not there....Can you tell me how to get the .CSV file with my required data...

Thank you
Nov 10 '08 #20
r035198x
13,262 8TB
You didn't forget to fclose(fp); did you?
Nov 10 '08 #21
ya....I haven't forget that....but I have solved the prob and it seems to be very simple...slapped of myself becoz of the prev thread,,looks like funny..I just forgot one '\' and for that I am struggling from half a day. Now it is OK....

Thanks for the reply
Nov 10 '08 #22
r035198x
13,262 8TB
Better make that two slaps.
Nov 10 '08 #23

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Trader | last post by:
Hi, I'm trying to use Mark Hammond's win32clipboard module to extract more complex data than just plain ASCII text from the Windows clipboard. For instance, when you select all the content on...
5
by: Henok Girma | last post by:
Hello Gurus, I wanted to have a very simple, strict regular expression validator for a phone field. the only valid format is (XXX) XXX-XXXX where X is a digit I have the following but it always...
1
by: worzel | last post by:
Hi All, I am looking for a reg ex that will match email addresses withing <a href=mailto blah > links. Actually, I already crafted my own, but with a slight problem: <a...
3
by: dave | last post by:
Hi there, I'm trying to extract formatting information from the columns in a database field and use it to format data bound text boxes in a VB6 application. I can't find a way to get the format...
0
by: sgsiaokia | last post by:
I need help in extracting data from another source file using VBA. I have problems copying the extracted data and format into the required data format. And also, how do i delete the row that is not...
6
by: Werner | last post by:
Hi, I try to read (and extract) some "self extracting" zipefiles on a Windows system. The standard module zipefile seems not to be able to handle this. False Is there a wrapper or has...
6
by: LeWalrus | last post by:
Hi, I've written a reg exp for capturing a group of numbers from text files in the following format: -1.4326 s < 0.6758 s < 1.4334 s Any of the numbers can be positive or negative and the units...
2
by: sivadhanekula | last post by:
Hi Everyone A quick question: How to write MYSQL command in C-Language MYSQL Statement to select particular row from a table is: SELECT User FROM absprfg where User is the heading of the...
2
by: sivadhanekula | last post by:
Hi everyone, I have a problem with my Mysql data. I have 2,95,67,456 lines of data which is too much and if I run this in MYSQL front-end it is telling "OUT OF MEMORY". Any way with my collegues...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.