Mysql 循环浏览数据库表并比较用户输入
我正在尝试循环MySql表中的行,并使用C将特定列中的数据与某些用户输入进行比较。目前我的代码如下所示:Mysql 循环浏览数据库表并比较用户输入,mysql,c,Mysql,C,我正在尝试循环MySql表中的行,并使用C将特定列中的数据与某些用户输入进行比较。目前我的代码如下所示: MYSQL *cxn = mysql_init(NULL); MYSQL_RES *result; unsigned int num_fields; unsigned int num_rows; char *query_string; MYSQL_ROW *row; if (mysql_real_connect(cxn, <em>/*blah blah blah**/</
MYSQL *cxn = mysql_init(NULL);
MYSQL_RES *result;
unsigned int num_fields;
unsigned int num_rows;
char *query_string;
MYSQL_ROW *row;
if (mysql_real_connect(cxn, <em>/*blah blah blah**/</em>) == NULL) {
printf("Please restart the service.");
}
result = mysql_store_result(cxn);
num_rows = mysql_num_rows(result);
num_fields = mysql_num_fields(result);
while (row = mysql_fetch_row(result)) {
for (i = 0; i < num_fields; i++) {
//Confusion occurring here
//if (field[i] @ currentRow == "User input")
// printf("Win");
}
}
如果只查找与输入匹配的字段,则需要使用输入字符串搜索数据库。换句话说,编写查询字符串,使其只提供与用户输入匹配的结果。这将比在返回的每一行中搜索用户输入快得多 从Cars=输入的表格中选择* 如果您确实需要返回每一行,那么您希望您的代码读取如下内容
while (row = mysql_fetch_row(result)) {
for (i = 0; i < num_fields; i++) {
//Confusion occurring here
//if (row[i] == "User input") You can't compare strings in C with ==
if(strcmp(row[i], user_input) == 0))
printf("Win");
}
}
无论@在C中做什么,您都无法将字符串值与C中的==进行比较。您需要一个库函数,如strcmp或自制函数。注释行中的“@”和其他所有内容都只是伪代码。为什么要迭代SQL数据库以查找某些内容?使用SELECT可以立即找到它,并让SQL引擎完成它的工作……我希望比较预先指定字段中的数据。比如,如果用户在Mustang中键入,我想在Car下查找并比较该字符串在Car下的所有值。你的意思是只比较特定列吗?Car是列标题吗?我想将指定列中的所有数据项与用户输入的字符串进行比较。您是否可以通过如下方式构造查询语句来解决此问题:SELECT*FROM`table`WHERE Car=input?请记住,SQL在搜索数据时几乎总是比您自己编写的循环更快搜索始终尝试在查询中查找数据,而不是在循环中查找数据。
if(strcmp(row[i], user_input) == 0))