user5431949
user5431949

Reputation:

How to return the value of SELECT COUNT in C

Well I was wondering if it is possible to use the result of count counts in a printf.

I have a code that does the count in mysql.

void count_sql(void) {

    if (SQL_ENTER == SQL_ROWS(mysql, "SELECT COUNT(*) FROM `login_client` WHERE `ID` < DATE(NOW() + INTERVAL 1 DAY)"))
        sqldebug(mysql);

    printf("Counted users\n");
    return;
}

I wanted to return the count value by leaving the message as below for example:

printf("150 users were found\n");

Upvotes: 1

Views: 3122

Answers (1)

Jpsh
Jpsh

Reputation: 1726

I was unable to find a data type similar to SQL_ENTER so I'm not sure if this is a variable or not in your code, here is the documentation I was looking at

26.8.7 C API Function Descriptions below I included my int main but you should be able to use just the void count_sql, also worth noting I passed the MYSQL object to the fucntion this could have also been part of your issue.

also worth noting I built and tested this code on a windows environment using MinGW compiler and the mysql-connector-c-6.1.9-win32 library so it might not work in your environment

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

int main(){
    /* initialize MYSQL connection */
    MYSQL *mysql = mysql_init(NULL);

    if(mysql == NULL){
        sqldebug(mysql);
    }

    /* pass credentials here */
    if(mysql_real_connect(mysql, "localhost", "user", "password", "database", 0, NULL, 0) == NULL){
        sqldebug(mysql);
    }

    /* run query and count results */
    count_sql(mysql);

    /*close connection and exit void*/
    mysql_close(mysql);
    exit(0);
}

void sqldebug(MYSQL *mysql)
{
  fprintf(stderr, "%s\n", mysql_error(mysql));
  mysql_close(mysql);
  exit(1);
}

void count_sql(MYSQL *mysql){
    /* run query */
    if(mysql_query(mysql, "SELECT COUNT(*) FROM `login_client` WHERE `ID` < DATE(NOW() + INTERVAL 1 DAY)")){
        sqldebug(mysql);
    }

    /* store the results */
    MYSQL_RES *result = mysql_store_result(mysql);

    if(result == NULL){
        finish_with_error(mysql);
    }

    /* check the result has records ** don't really need this part */
    int num_fields = mysql_num_fields(result);
    if(num_fields<1){
        printf("no fields returned");
        exit(1);
    }

    /* row record */
    MYSQL_ROW row;

    if(row=mysql_fetch_row(result)){
       printf("Counted users %s\n", row[0]);
    }
    return;
}

Upvotes: 2

Related Questions