I have the below MySQL query which when done in the MySQL console shows the correct result. I can't figure out how to store the result into a variable in my c program however.
Here is the code that I type into the MySQL interface:
mysql> SELECT id FROM Stations where name = 'AE0';
This is what it returns:
+----+
| id |
+----+
| 1 |
+----+
I need the above value of '1' stored into a variable in my c program. The MySQL query is called from my c program using this code:
MYSQL_RES *result;
MYSQL_ROW row;
length=sprintf(query,"SELECT id FROM Stations where name ='AE0'");
myquery(conn,query,length);
result=mysql_store_result(conn);
row=mysql_fetch_row(result);
I'm unsure if the value I'm looking for is stored in 'result', whether it is or isn't, how can I find it and save it into an integer?
short answer:
int i = atoi(row[0]);
long answer:
http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html
Returns a MYSQL_ROW. You then have to iterate through the row to get each value. Those values are strings, so you'll need to convert them to int with atoi()
. This is demonstrated in the code below (except the atoi()
call) shamelessly stolen from the link above:
MYSQL_ROW row;
unsigned int num_fields;
unsigned int i;
num_fields = mysql_num_fields(result);
while ((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
printf("[%.*s] ", (int) lengths[i],
row[i] ? row[i] : "NULL");
}
printf("\n");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.