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

标签 c++ sqlite

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

id|itemName
 1|noodle
 2|burger

基本上我想问的是,我是否可以将输入结果与我的数据库进行比较 记录?

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

#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;
}

最佳答案

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

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);

关于c++ - 将结果与用户输入进行比较 - sqlite3 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352459/

相关文章:

c++ - 如何判断 libcurl 是否正确处理了我的 SSL 文件

c++ - 对 unordered_map 使用 equal_range

mysql - 按月份范围选择记录

python - 一种用于跟踪数据库中表历史记录的命令行/API 工具,它是否存在,或者我应该去开发一个吗?

java - 安卓 SQLite : Data being added again and again

c++ - Microsoft 使用什么作为 Unicode 字符串的数据类型?

c++ - ADO 命令执行失败

c++ - 当构建有错误时,Eclipse C++ 从不运行

sqlite - .db 和 .sqlite 文件的区别

Django反向查询集包含列表中的所有值