如何使用C++检查 sqlite 列中是否"value does not exists"

How to check if "value does not exists" in sqlite column using C++

本文关键字:value does not exists 是否 C++ 何使用 检查 sqlite      更新时间:2023-10-16

我有一个表"SiteCode",具有以下架构:

CREATE TABLE SiteCode(
ID INTEGER PRIMARY KEY,
Code TEXT(3) UNIQUE NOT NULL DEFAULT 0);

通过以下代码,我可以打开一个DB&访问数据库的元素并完美地执行查询。

现在我想添加一个小代码片段,它可以检查用户想要删除的元素是否存在。

例如:假设表SiteCodeCode列中有以下条目:400401402403并且用户输入444作为DELETE查询的输入,那么它将返回一个错误。

目前,如果用户输入444作为查询的输入,则该查询将成功执行,而无需检查代码列,也无任何错误

我该如何处理这个问题。请帮忙。

void DELETE_Site_Code()
{
     int CodeA;
     int rc = sqlite3_open("/DBsqlite3/empdbv3.db", &db);
     if (rc != SQLITE_OK) {       
         cerr << "Cannot open database [ " << sqlite3_errmsg(db) << " ]" << endl;        
         sqlite3_close(db);        
     }

     sql = "DELETE FROM SiteCode WHERE Code= @Code;";
     rc = sqlite3_prepare_v2(db, sql, -1, &stmt4, 0);
     if(SQLITE_OK != rc) {
         cerr << "Failed to PREPARE DELETE statement for SiteCode Table [ " << sqlite3_errmsg(db) << " ]" << endl;
         sqlite3_close(db);
         exit(1);
     }
     else{
         int Code_x = sqlite3_bind_parameter_index(stmt4, "@Code");
         cout<< "Enter the Site Code That you wish to DELETE from table-SiteCoden"<< endl;
         cin>>CodeA;                                                     
         if(cin.fail()) {
             cout<<"nPlease enter only digitsn"<<endl;
         }
         else {
             if((CodeA >= 000) && (CodeA <= 998)) {
                 sqlite3_bind_int(stmt4, Code_x, CodeA);
             }
             else {
                 cout<< "Valid Site Code Should be between 000 to 998n" <<endl;
             }
         } //else loop of (cin.fail) ends here
     }
    int step = sqlite3_step(stmt4);
    if(SQLITE_DONE != step) {
        cout<<"nERROR while inserting into tablen"<< endl;
    } 
    else {
        cout<<"nRecord DELETION completed"<<endl;
    }
    if(step == SQLITE_ROW){
        cout<< sqlite3_column_text(stmt4, 0) << endl;
        cout<< sqlite3_column_text(stmt4, 1) << endl;
    }

    sqlite3_finalize(stmt4);
    sqlite3_close(db);
}

使用sqlite3_changes()函数查询最近执行的查询影响了多少行:

// ...
int step = sqlite3_step(stmt4);
if(SQLITE_DONE != step) {
    cout<<"nERROR while inserting into tablen"<< endl;
} 
else if (sqlite3_changes(db) == 0) {
    cout<<"nNo records deleted"<<endl;
}
else {
    cout<<"nRecord DELETION completed"<<endl;
}