473,545 Members | 2,388 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reg: Extracting the data to CSV format

58 New Member
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 3208
donbock
2,426 Recognized Expert Top Contributor
Do you have a specific question?
... Are you getting a build error?
... Is the program malfunctioning?
Nov 3 '08 #2
sivadhanekula
58 New Member
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 MVP
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
sivadhanekula
58 New Member
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 MVP
You need to use mysql_query (or mysql_real_quer y) for the select statement from the tables themselves then use mysql_use_resul ts to process the results. You can about all that from the refmanual itself.
P.S Your English is fine.
Nov 4 '08 #6
sivadhanekula
58 New Member
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 MVP
Now read my reply #4 above again.
Nov 5 '08 #8
sivadhanekula
58 New Member
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 Recognized Expert Moderator Expert
Did you put this

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

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

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

Similar topics

2
3716
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 web page, you can paste it into an app like Frontpage, or something Rich Text-aware, and it will preserve all the formatting, HTML, etc. I'd like to...
5
1762
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 evaluates to false var reg = new RegExp("^\(\d{3}\) \d{3}-\d{4}$"); alert(reg.test("(123) 221-9244")); Any help is greatly appreciated..
1
1962
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 href="mailto:fred@blah.com"> emal me</a> woud be matched as expected, but so will:
3
1829
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 information from the ADO database fields. Can anyone help me at all, I'm really stuck and pretty desparate! An example, or a link to an example is...
0
1463
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 required in the output file, in the below example: The row, D0, is not needed. An Example Data Format From the SOURCE file: ...
6
4435
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 some one experience with other libaries to
6
1689
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 (s) can change or even be absent. What I wanted was the three numbers (signs included)! Here was the reg exp I used to capture: $line =~...
2
1990
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 row absprfg is the table name
2
1745
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 system I have got the runned data and I have copied it to my Frontend, now it works. But my problem is if I am extracting particular data from that it...
0
7487
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7420
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7680
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7934
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6003
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3476
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1908
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1033
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
731
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.