由于某些原因,我的C代码无法工作。SQL代码是正确的,当我将它运行到phpmyadmin中时,我得到了所需的结果,但是如果我运行这段代码,它似乎是空的。有趣的是,如果我删除
if((row = mysql_fetch_row(query_results)) !=0),或者如果我删除
while((row = mysql_fetch_row(query_results)) !=0)那我就能得到结果了。不知道为什么这两个人不能一起工作,但又各自工作得很好。
MYSQL_RES *query_results = mysql_store_result(conn);
if (query_results)
{ // make sure there *are* results..
MYSQL_ROW row;
if((row = mysql_fetch_row(query_results)) !=0)
{
while((row = mysql_fetch_row(query_results)) !=0)
{
printf("So far soo good 2\n");
/* Set a float 'f' to the value in 'row[0]', or
* 0.0f if it's NULL */
char *result_miner = row[0] ? row[0] : "NULL";
char *result_algorithm = row[1] ? row[1] : "NULL";
char *result_url = row[2] ? row[2] : "NULL";
int result_port = row[3] ? atof(row[3]) : 1;
char *result_username = row[4] ? row[4] : "NULL";
char *result_password = row[5] ? row[5] : "NULL";
strcpy(miner, result_miner);
strcpy(algorithm, result_algorithm);
strcpy(url, result_url);
strcpy(username, result_username);
strcpy(password, result_password);
port=result_port;
printf ("Miner Protocol is: %s\n", miner);
printf ("Algorithm is: %s\n", algorithm);
printf ("Mining URL is: %s\n", url);
printf ("Mining Port is: %d \n", port);
printf ("Username is: %s \n", username);
printf ("Password is: %s \n", password);
}
}else{
printf("Unable to locate active coin for hostname: %s", hostname);
exit (-1);
}
/* Free results when done */
mysql_free_result(query_results);发布于 2018-02-22 00:29:49
基于mysql_fetch_row,您必须这样做:
while((row = mysql_fetch_row(query_results)))
{
printf("So far soo good 2\n");
char *result_miner = row[0] ? row[0] : "NULL";
char *result_algorithm = row[1] ? row[1] : "NULL";
char *result_url = row[2] ? row[2] : "NULL";
int result_port = row[3] ? atof(row[3]) : 1;
char *result_username = row[4] ? row[4] : "NULL";
char *result_password = row[5] ? row[5] : "NULL";
....
}不需要添加将while放入if((row = mysql_fetch_row(query_results)) !=0)中,因为它将消耗一行,如果您说您只期望一行,那么这就解释了为什么您没有看到任何值。
文档指出,如果不能获取更多的行,mysql_fetch_row将返回NULL。您说您期望有1行,但可能会得到2行,其中一行的值为空。在while循环之前,可以使用mysql_num_rows()查看结果集中的实际行数。我怀疑您的查询结果为2行。
https://dev.mysql.com/doc/refman/5.7/en/mysql-num-rows.html my_ulonglong mysql_num_rows(MYSQL_RES *result) 描述 返回结果集中的行数。
mysql_num_rows()的使用取决于您是使用mysql_store_result()还是mysql_use_result()返回结果集。如果使用mysql_store_result()**,**mysql_num_rows(),则可能会立即调用。如果使用mysql_use_result(),则在检索结果集中的所有行之前,mysql_num_rows()不会返回正确的值。
编辑
如何使用mysql_num_rows。
MYSQL_RES *query_results = mysql_store_result(conn);
if(query_results)
{
printf ("Number of rows: %lu\n",
(unsigned long) mysql_num_rows(query_results));
while((row = mysql_fetch_row(query_results)))
...
}https://stackoverflow.com/questions/48917362
复制相似问题