mysql - C:MySQL SELECT 的动态结果集

标签 mysql c select

我当前正在将多维字符数组传递给我的 MySQL 函数。 cmd 包含命令,resultSet[2][50] 是我的数组。

如何使其更加动态,以便我能够检索尽可能多的项目?

int
selectDB(char * cmd, char resultSet[2][50])
{
    MYSQL *conn;
    MYSQL_RES *result;
    MYSQL_ROW row;
    int i;
    char *c1;

    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", "myDBName", 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++)               
                {
                snprintf(resultSet[i], 999, "%s", 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;
}

最佳答案

您可以接受一个三重指针作为参数,就像这样和一个int,它将告诉数组的大小

int selectDB( char* cmd, char*** resultSet, int* m, int* n )
{
    // allocate two dimentional array with any size you want, using malloc
    // store the size into m and n
    // do stuff with resultSet
    // watch out when using snprintf - check if i is smaller
    // than the size of the array. If so - just use snprintf
    // otherwise, you'll need to allocate some larger memory, 
    // and copy "move" the current records into the new location
    // then free the old memory, etc.
    // 
    // return
}

这样您就可以知道数组的大小,但您需要释放为 resultSet 分配的内存。

关于mysql - C:MySQL SELECT 的动态结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5980226/

相关文章:

mysql - 如何创建子查询

c - 如何初始化包含指向指针的指针的结构

c - 链接列表节点插入到前面 - 每次添加值时所有内容值都会改变

jquery - SelectBox 替换,允许选项中的 html

Android 5.0 在 webview 中选择标签为空

mysql - 来自 MYSQL 数据库的 MS Access 报告

mysql - 解释MySQL中的函数

c - STM32闪烁的LED错误寄存器?

mysql - 获取百分比平均值

Python+mysql - 在for循环中构建插入语句