I have this weird behavior in C which I do not understand. It is probably me as I am fairly new to C. What I am trying to achieve is to write a function that runs a MySQL query and returns the result. The weird thing is that, in the code below, if I close the connection and free the result (as I would expect the order to be) it seems that the value that I have stored in ‘retvalue’ is no longer there. When I put the return before the freeing of the result and closing of the connection the value is returned, but obviously the connection is not closed and MySQL will eventually present the error ‘too many connections’.
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;
}
So the questions are:
Am I right to assume that first freeing the result and closing the connection is the right order?
and why is the value that I have assigned to retvalue gone when I run the function like this?
Thanks for being nice to a beginner 🙂
The cast
retvalue = (int)row[0]is wrong. It puts the address of the result (converted to int) inretvalue.row[0]is achar*, so you should useretvalue=atoi(row[0]).