mysql - 在 C API 中检索 MySQL *con 值

标签 mysql c

我正在尝试从 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/

相关文章:

c - 我的 program.exe 已停止工作

c - "Hello World"会打印多少次?

mysql - 错误 2002 (HY000) : Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' - Missing files

php - 如何计算每页使用的 MySQL 查询总数?

c - 是否有一种符合 ISO C 的方法来创建一个返回指向嵌套在其中的函数的指针的函数?

CryptoApi 到 CommonCrypto

c - 树函数的递归代码?

mysql - 为什么我不能将带有触发器的 mysql 转储导入 mariadb

php - 如何在 WHERE 子句中使用同一列中的多个值?

php - 使用连接库时如何在 codeigniter 上创建别名