Return result from MySQL query to function after closing connection in C

I have this weird behavior in C that I don't understand. This is probably me, since I'm pretty new to C. What I'm trying to achieve is to write a function that launches a MySQL query and returns a result. The strange thing is that in the code below, if I close the connection and release the result (as expected, the order will be), it seems that the value that I saved in the 'retvalue' no longer exists. When I return the result before releasing the result and closing the connection, the value is returned, but obviously the connection is not closed, and MySQL will ultimately present an “too many connections” error.

int CheckBox(char *mac)
{
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;

/* database details */
char *server = "localhost";
char *user = "user";
char *password = "pw";
char *database = "db";
int retvalue;

conn = mysql_init(NULL);

/* connect to database */
if (!mysql_real_connect(conn, server,user, password, database, 0, NULL, 0))
{
    fprintf(stderr, "%s\n", mysql_error(conn));
    exit(1);
}

/* create and send SQL query */
char query[1600];
sprintf(query,"SELECT * FROM boxes WHERE mac = '%s'", mac);
if (mysql_query(conn, query))
{
    fprintf(stderr, "%s\n", mysql_error(conn));
    exit(1);
}

res = mysql_use_result(conn);
/* check result to see if we have a hit */
if ((row = mysql_fetch_row(res)) != NULL)
{

    printf("mac (%s) did exist with id %s.\n",mac,(char *)row[0]);
    retvalue = (int)row[0];
} else
{
    printf("mac (%s) did NOT exist ",mac);
    /* mac address did not yet exist, so create it */
    sprintf(query,"INSERT INTO boxes (mac) VALUES ('%s')",mac);
    if (mysql_query(conn, query))
    {
        fprintf(stderr, "%s\n", mysql_error(conn));
        exit(1);
    } else
    {
        printf("but now does\n");
        CheckBox(mac);
    }
}

/* close connection */
mysql_free_result(res);
mysql_close(conn);

/* return id number of box */
return retvalue;
}

, : , - ? , retvalue, , ​​?

, : -)

+3
1

retvalue = (int)row[0] . ( int) retvalue. row[0] - char*, retvalue=atoi(row[0]).

+4

All Articles