By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,470 Members | 1,482 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,470 IT Pros & Developers. It's quick & easy.

Reg: Extracting the data to CSV format

P: 58
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
Share this Question
Share on Google+
22 Replies


Expert 100+
P: 2,415
Do you have a specific question?
... Are you getting a build error?
... Is the program malfunctioning?
Nov 3 '08 #2

P: 58
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

10K+
P: 13,264
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

P: 58
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

10K+
P: 13,264
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

P: 58
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

10K+
P: 13,264
Now read my reply #4 above again.
Nov 5 '08 #8

P: 58
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
Expert Mod 5K+
P: 8,916
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

P: 58
Hmmmm again the same error !!!!!
Nov 6 '08 #11

10K+
P: 13,264
Let's see the code you used.
P.S Just post the part around which the error is being reported.
Nov 6 '08 #12

P: 58
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
Expert Mod 5K+
P: 8,916
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

P: 58
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

10K+
P: 13,264
Read my post number 4 again.
Do you understand the meaning of the word "redirect"?
Nov 7 '08 #16

P: 58
Sorry....I didn't get you...Can you tell me reg that briefly.....

ThanQ
Nov 7 '08 #17

10K+
P: 13,264
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

P: 58
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

P: 58
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

10K+
P: 13,264
You didn't forget to fclose(fp); did you?
Nov 10 '08 #21

P: 58
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

10K+
P: 13,264
Better make that two slaps.
Nov 10 '08 #23

Post your reply

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