我正在尝试从 mySQL 数据库中检索数据。我写了一个函数来做到这一点。但是当线程返回到main()时,con中的值全部为NULL。我不知道为什么。我使用 Xcode 对此进行调试。
其实昨天还好好的。我只是想改变我的程序的路径,然后它失败了。即使我把它改回来,它仍然不起作用了。而且我写了一个小程序来测试连接,也是同样的问题。
下面是我试过的小程序。他们有同样的问题。
#include "fun.h"
int main(void) {
MYSQL* con;
int num;
int* p_num=#
change_num(p_num);
printf("[%d]Hello, World!\n",num);
// After the execution, con is still NULL.
MYSQLInit(con);
if (con==NULL) {
finish_with_error(con);
}
return 0;
}
函数文件:
#include "fun.h"
void MYSQLInit(MYSQL* con){
con=mysql_init(NULL);
if (con == NULL)
finish_with_error(con);
/* mySQL login */
if (mysql_real_connect(con, "85.235.3.37", "July", "0000",
NULL , 0, NULL, 0) == NULL)
{
finish_with_error(con);
}
if (mysql_query(con, "USE lamp")) {
finish_with_error(con);
}
// con has correct value here
}
void finish_with_error(MYSQL *con)
{
fprintf(stderr, "%s\n", mysql_error(con));
mysql_close(con);
exit(1);
}
void change_num(int* p_num){
*p_num=10;
}
最佳答案
您需要再取消引用一个级别:
void MYSQLInit(MYSQL **con)
{
*con = mysql_init(NULL);
// ...
}
然后,调用:
MYSQLInit(&con);
或者,您可以从您的函数返回 MYSQL *
,例如:
MYSQL *MYSQLInit()
{
MYSQL *con = mysql_init(NULL);
// ...
return con;
}
然后这样调用:
con = MYSQLInit();
关于mysql - 在 C API 中检索 MySQL *con 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31455222/