Hi All,

Im currently try to write a code to read the data from mysql tables and then write the contents into a text file. Below is my code. I dunt know what's wrong with this code because in the text file created, there is no data from database written. Hope u guys can help me..

Thanks in advance..:)

#include <stdio.h>
#include <string.h>
#include <mysql.h>

#define HOST "localhost"
#define USER "yati"
#define PASSWD "yati"
#define DB_NAME "subscriberTool"

void openFile();
void readFromDB(); 

static MYSQL demo_db;
//char hp[50], startdate[50], enddate[50];
    
int main()
{
    openFile();
}


void openFile()
{
    
    char line[1600];
    char lineone[1600];
    char hp[50], startdate[50], enddate[50];
    FILE *fp;

    fp=fopen("TH.txt", "w");

    if(fp==NULL) 
    {
        printf("file cannot be opened!\n");
        exit(0);
    }
    else {

        while(!feof(fp)) 
        {
            bzero(line, sizeof(line));
            fgets(line,1600,fp);
            readFromDB();
            sprintf(lineone, "%s,%s,%s", hp, startdate, enddate);
            printf("Error");
        }


        }


    fclose(fp);
    return;
}

void readFromDB()
{
    char query[16384];
    char query1[16384];


    if(!mysql_connect(&demo_db, HOST, USER, PASSWD))
        {
            printf(mysql_error(&demo_db));
        exit(1);
        }

        if(mysql_select_db(&demo_db, DB_NAME))
        {
            /* Select the database we want to use */
            printf(mysql_error(&demo_db));
        exit(1);
        }
           
      bzero(query, sizeof(query1));

        sprintf(query, "SELECT MobileNumber,StartDate,EndDate FROM Subscriptions order by StartDate asc");   
        mysql_query(&demo_db, query1);

      printf("%s\n",query);

      if(mysql_real_query(&demo_db, query, strlen(query)+255))
        {
           printf(mysql_error(&demo_db));
            bzero(query, sizeof(query));
             exit(1);
        }

    mysql_close(&demo_db);

    return;
}

Dani AI

Generated

The empty output file comes from a combination of logic and API mistakes: the program opens TH.txt for writing then immediately tries to read from it, the DB routine runs queries but never calls mysql_store_result()/mysql_fetch_row() to retrieve rows, several buffer/variable mistakes (bzero on the wrong buffer, calling mysql_query with the wrong string), and the connection is closed before any results are processed. was right to call out the missing “fetch rows and write them” step; this needs a concrete I/O loop and proper error checks.

Key points to follow (brief):

  • Initialize and connect with mysql_init/mysql_real_connect, check return values.
  • Run the SELECT, call mysql_store_result (or mysql_use_result), then loop with mysql_fetch_row to get each row.
  • Open the output file once (fopen) and write each fetched row with fprintf; do not drive loops with feof().
  • Free the result (mysql_free_result), close file, then close the DB connection.
  • Check mysql_error(conn) after any failing call and handle NULL fields when printing CSV-style output.

Example minimal pattern (adjust names/paths as needed):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>

int main(void) {
    MYSQL *conn = mysql_init(NULL);
    MYSQL_RES *res;
    MYSQL_ROW row;
    FILE *fp;

    if (!mysql_real_connect(conn, "localhost", "yati", "yati", "subscriberTool", 0, NULL, 0)) {
        fprintf(stderr, "connect error: %s\n", mysql_error(conn));
        return 1;
    }

    if (mysql_query(conn, "SELECT MobileNumber, StartDate, EndDate FROM Subscriptions ORDER BY StartDate ASC")) {
        fprintf(stderr, "query error: %s\n", mysql_error(conn));
        mysql_close(conn);
        return 1;
    }

    res = mysql_store_result(conn);
    if (!res) { mysql_close(conn); return 1; }

    fp = fopen("TH.txt", "w");
    if (!fp) { perror("fopen"); mysql_free_result(res); mysql_close(conn); return 1; }

    while ((row = mysql_fetch_row(res)) != NULL) {
        fprintf(fp, "%s,%s,%s\n", row[0] ? row[0] : "", row[1] ? row[1] : "", row[2] ? row[2] : "");
    }

    fclose(fp);
    mysql_free_result(res);
    mysql_close(conn);
    return 0;
}

This implements the practical steps behind ’s advice and keeps the resource-lifetime points mentioned in mind. If the file is still empty, verify the SELECT returns rows by running it in the mysql client and confirm credentials and database name are correct. Also consider quoting/escaping fields if commas/newlines appear in data.

Recommended Answers

All 4 Replies

>>there is no data from database written.

Read you program again. Where does it even attempt to write anything to the text file? Where does your program call readFromDB() to get the row from the table? You program consists of two functions, one function that just opens a file then immediately closes it. And a second function that opens the database and executes a query -- it just ignores the result set. Nowhere does your program put those two functions together. You need to do something like this

OPEN THE TEXT FILE FOR WRITE
OPEN THE DATABASE
QUERY THE DATABASE
CALL mysql_field_count() TO SEE IF THE QUERY RETURNED A RESULT SET
FOR EACH RESULTSET ROW (one of the mysql_fetch??? functions)
   WRITE RESULT ROW TO TEXT FILE

CLOSE THE DATABASE
CLOSE THE TEXT FILE

You need to be familiar with the if you want to write a program that queries a mysql database.

CAN YOU BE ABIT MORE SPECIFIC ON THIS PLEASE? I AM SORRY I AM QUITE NEW BUT I AM VERY INTERESTED..PLEASE~
:eek:

OPEN THE TEXT FILE FOR WRITE
OPEN THE DATABASE
QUERY THE DATABASE
CALL mysql_field_count() TO SEE IF THE QUERY RETURNED A RESULT SET
FOR EACH RESULTSET ROW (one of the mysql_fetch??? functions)
   WRITE RESULT ROW TO TEXT FILE

CLOSE THE DATABASE
CLOSE THE TEXT FILE

You need to be familiar with the if you want to write a program that queries a mysql database.

You should at least be quite familiar with C/C++ before starting database I/O.

I'd start by reading some of the many available out there. Once you begin to get the hang of it, you'll probably want to further your knowledge by reading the MySQL documentation as Ancient Dragon suggested.

CAN YOU BE ABIT MORE SPECIFIC ON THIS PLEASE? I.
.

Sorry, but you wouldn't understand even if I did post something more specific. Learn to crawl before you try to walk, and learn to walk before you try to run. When you know how to run then you will have little if any problems understanding how to do what you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.