我当前正在将多维字符数组传递给我的 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/