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;
char *server = "localhost";
char *user = "user";
char *password = "pw";
char *database = "db";
int retvalue;
conn = mysql_init(NULL);
if (!mysql_real_connect(conn, server,user, password, database, 0, NULL, 0))
{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
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);
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);
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);
}
}
mysql_free_result(res);
mysql_close(conn);
return retvalue;
}
, :
, - ?
, retvalue, , ?
, : -)