mysql - C程序: Segmentation fault when selecting from MySQL with field that contains NULL

标签 mysql c null

这一切似乎都有效,但如果其中有一个带有 NULL 的 MySQL 字段,我会得到一个段错误。

代码如下:

int 
selectDB(char * cmd)
{
    printf("Cmd: %s\n", cmd);
    MYSQL *conn;
    MYSQL_RES *result;
    MYSQL_ROW row;
    int i;

    conn = mysql_init(NULL);

    if (conn == NULL) {
        printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
        exit(1);
    }

        if (mysql_real_connect(conn, "localhost", "root",
    "myPassword", "myDB", 0, NULL, 0) == NULL)
    {
        printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
        exit(1);    
    }

    if (mysql_query(conn, cmd)) 
    {
        printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
        exit(1);
    }

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

    while((row = mysql_fetch_row(result))) {
        for (i=0 ; i < mysql_num_fields(result); i++) 
            printf("%s\n", row[i]);
    }

    if (!mysql_eof(result))
    {
        printf("Error %u: %s\n", mysql_errno(conn), mysql_error(conn));
        exit(1);
    }

   mysql_free_result(result);   
    mysql_close(conn);
    return 0;
}

我正在调用它

char cmd[1000];
snprintf(cmd, 999, "SELECT * FROM users WHERE id = %s", valueptr);
selectDB(cmd);

最佳答案

来自 the MySQL docs :

NULL values in the row are indicated by NULL pointers. 

你需要这样的东西:

 for (i=0 ; i < mysql_num_fields(result); i++) 
        printf("%s\n", row[i] ? row[i] : "NULL" );

关于mysql - C程序: Segmentation fault when selecting from MySQL with field that contains NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5874123/

相关文章:

php - php/mysql存储海量数据复杂关系的最佳方式

c - 如何解析从套接字接收的字符串?

c - scanf 并指向 int* 段错误

mysql - mysql 日期返回空值和非空值

design-patterns - KeyNotFoundException 与在 Kotlin 中返回 null

php - CakePHP 3.0 在哪里放置查询

MySQL性能;大数据表还是多数据表?

php - Magento 多站点 - 批量启用和设置每个站点不同的可见性

c - atan2f vs fmodf vs 只是简单的减法

ruby-on-rails - 在查询中使用 'nil' 和 `group` 时,哈希值为 `count`