0

我正在尝试在 C 中执行 MySQL 查询,但是在调用 mysql_num_rows() 时出现分段错误。

这是我正在使用的代码:

char *username = "test@mail.com";
char *password = "pass";

char query[1000];
int len;
char *q = "SELECT * FROM Users WHERE `Email` = '%s' AND `Password` = '%s'";
len = snprintf(query, strlen(q) + strlen(username) + strlen(password), q, username, password);
MYSQL_RES *result;
if (db_query(query, result))
{
if (result != NULL)
{
    int test_count = mysql_num_rows(result);
    printf("%d\n", test_count);
}
}
else
{
printf("Query error\n");
}

这是 db_query() 函数:

bool db_query(const char *query, MYSQL_RES *result)
{
    if (mysql_query(db_connection, query))
    {
     printf("mysql_query(): Error %u: %s\n", mysql_errno(db_connection), mysql_error(db_connection));

     return false;
    }

    if (!(result = mysql_store_result(db_connection)))
    {
    printf("mysql_store_result(): Error %u: %s\n", mysql_errno(db_connection), mysql_error(db_connection));

    return false;
    }

    return true;
}

我已经测试了查询并且问题不存在,连接也已启动。有任何想法吗?

谢谢!

4

2 回答 2

3

你的问题在这里,在db_query函数中:

if (!(result = mysql_store_result(db_connection)))

对函数的调用者的赋值result没有明显的影响——你通过值传递一个指针,改变被调用者的值对result调用者没有任何作用result

您需要更改函数以采用指针对指针,并调整调用站点和db_query函数。

bool db_query(const char *query, MYSQL_RES **result)
{
  ...
  if (!(*result = mysql_store_result(db_connection)))
  ...
}
于 2013-05-05T12:29:43.550 回答
2

函数中的任何更改都result不会反映调用者,因此它仍将包含它在创建时所具有的任意值(作为没有初始化的自动变量。db_query

如果要更改值并将其反映回来,则应将双指针传递给它,然后取消对双指针的引用以获取实际值。

更好的是返回result值并将其 NULL/非 NULL 状态用于成功代码,而不是返回true/false.

于 2013-05-05T12:29:59.157 回答