MySQL C API: how to work with a string from mysql_fetch_row ()?

This is a sample code from my application:

int page_id; string page_name; enum COLUMNS { PAGE_ID, PAGE_NAME }; if (mysql_query(conn, "SELECT page_id, page_name FROM pages")) { exit_mysql_error(conn); } MYSQL_RES *res = mysql_use_result(conn); while (MYSQL_ROW row = mysql_fetch_row(res)) { page_id = *(int *)res[PAGE_ID]; page_name = res[PAGE_NAME]; // do some stuff where I need the page_id and page_name int/string } 

So imho is not the right way to get the integer value from the result (but it works), but I could not find a good example of how to do this. I'm also quite new to C ++ programming, so any feedback on sample code is welcome.

+4
source share
3 answers
 page_id = atoi(row[0]); page_name = row[1]; // not really sure 
+4
source

Here you can find a complete example of how to use the Mysql API in C / C ++:

Writing to mysql database from one on-board computer using c

To get your fields:

 while ((row = mysql_fetch_row (query_result))) { /* Each field in represented by the string row[i] */ /* If the field you want to extract is an int, so you need to convert it */ page_id = atoi(row[i]); page_name = row[2]; last_filed = row[number_of_fields_in_your_table - 1]; } 

You can also create a buffer with the result of your request and parse it using a separator

 while ((row = mysql_fetch_row (query_result))) { memset(buffer, '\0', sizeof(buffer)); for (i = 0; i < num_fields - 1; i++) { strncat(buffer, row[i], strlen(row[i]) + 1); strncat(buffer, ";", 2); } /* After this your buffer will contain * buffer = "page_id;page_name;...;" * and you can retreive all fields with snprintf for example */ snprintf(buffer, sizeof(buffer), "%d;%s;...", page_id, page_name,...); } 
+4
source

You can use stringstream

  std::istringstream strStream(res[PAGE_ID]); strStream >> page_id; 

you will need #include<sstream> for this. Here I assume that your PAGE_ID value is correctly set to the column index to get the right column. I suggested from the question that your only concern is casting from string to int* and that your column indices are already correct

+3
source

All Articles