我在C中有这种奇怪的行为,我不理解.因为我对C相当陌生,所以可能是我.我试图实现的目标是编写一个运行MySQL查询并返回结果的函数.奇怪的是,在下面的代码中,如果我关闭连接并释放结果(正如我期望的顺序那样),似乎我存储在“ retvalue”中的值不再存在.当我在释放结果和关闭连接之前放置return时,返回值,但是显然连接没有关闭,MySQL最终将显示错误“连接太多”.
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
", 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
", 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.
",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
", mysql_error(conn));
exit(1);
} else
{
printf("but now does
");
CheckBox(mac);
}
}
/* close connection */
mysql_free_result(res);
mysql_close(conn);
/* return id number of box */
return retvalue;
}
所以问题是:
我是否应该假设首先释放结果并关闭连接是正确的顺序?
当我运行这样的函数时,为什么我分配给retvalue的值消失了?
感谢您对初学者很好:-)