将结果与用户输入进行比较 - sqlite3 c ++

时间:2014-01-25 15:29:44

标签: c++ sqlite

我有一个表(Item),其属性为id,item

id|itemName
 1|noodle
 2|burger

基本上我想问一下,无论如何我可以将输入结果与我的数据库进行比较 记录?

例如,如果我输入面条,并且我的数据库中有匹配的记录“noodle”,它将返回找到;

#include <stdio.h>
#include <stdlib.h>
#include <sqlite3.h> 
#include <string>
#include <iostream>
#include <string.h>
#include <stdio.h>      
#include <stdlib.h> 



static int callback(void *NotUsed, int argc, char **argv, char **azColName){
   int i;
   for(i=0; i<argc; i++){
      printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   printf("\n");
  return 0;
}

int main(int argc, char* argv[])
{
    sqlite3 *db;
    char *zErrMsg = 0;
    int  rc;
    const char *sql;
    std::string itemName;

    rc = sqlite3_open("test.db", &db);
    if( rc ) {
    // failed
        fprintf(stderr, "Can't open database: %s\n", 
              sqlite3_errmsg(db));
    }
    else
    {
    // success
        fprintf(stderr, "Open database successfully\n");
    }


    std::cout << "Enter a Item" << std::endl;
    std::cin >> itemName;  
    sql = "select * from Item";         
    rc = sqlite3_exec(db,sql, callback, 0, &zErrMsg);
    if(//how do I compare the itemName from my database against the user input)
    {
    }
    sqlite3_close(db);

    return 0;
}

1 个答案:

答案 0 :(得分:2)

您可以使用参数来指定所需的记录,而不是回调:

std::cin >> itemName;  
sql = "select id from Item where itemName = ?";    

sqlite3_stmt *stmt;
sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);

// set the ? parameter to the itemname you are looking for:
sqlite3_bind_text(stmt, 1, itemName.c_str(), -1, SQLITE_TRANSIENT);

if(sqlite3_step(stmt) == SQLITE_ROW )
{
    int id=sqlite3_column_int(stmt,0);
    std::cout << "Found id=" << id << std::endl;
}

sqlite3_finalize(stmt);
sqlite3_close(db);