Googlebot
Googlebot

Reputation: 15673

How to save MySQL results into an array via C API?

I retrieve rows via C API.

MYSQL_ROW row;
int i=0;
char* A[100];
while ((row = mysql_fetch_row(result))){
    A[i]=row; // My Question
    i++;
}

mysql_free_result(result);
mysql_close(con);

for(int i=0;i<sizeof(A);i++){
    printf("%s\n",A[1]);
}

How can I save the entire rows in an array, independent of MySQL connection?

Upvotes: 0

Views: 159

Answers (1)

fpiette
fpiette

Reputation: 12292

You have to duplicate the field value.

For example, duplicating only the first field:

#define MAX_REC 100
MYSQL_ROW row;
unsigned int i;
char* A[MAX_REC];

i = 0;
while ((i < MAX_REC) && (row = mysql_fetch_row(result))) {
    // Copy first field only (Create a duplicate that must be freed later)
    A[i] = row[0] ? strdup(row[0]) : "NULL";
    i++;
}

If you need all fields, an inner loop and a 2D array is necessary. Don't forget to free all duplicated values when no more needed!

Upvotes: 2

Related Questions