I'm currently passing a multidimensional char array to my MySQL function. cmd contains the command and resultSet[2][50] is my array.
How can I make this more dynamic so that I'm able to retrieve as many items as I want?
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;
}
You could accept a triple pointer as an argument like this and an int
, that will tell the size of the array
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
}
This way you'll know the size of the array, but you'll need to take care of freeing the memory, allocated for resultSet
.
精彩评论