Home > OS >  C , use of % to search and find all with same first name in a database
C , use of % to search and find all with same first name in a database

Time:03-07

Here I got a database request where I want to search for a name, and then print the information for that name. What I am struggling to find out is when I search for Peter, I want all Peter ... to show, both firstname and surname. Somehow with use of %. Grateful for help.

 void search_stud(SQLite::Database &db)
{
    string student_nm;

    SQLite::Statement query6 (db, "SELECT * from students WHERE name = ?");

    cout << "Enter student name: " << endl;
    getchar();
    getline(cin, student_nm);

    query6.bind(1, student_nm);

    while (query6.tryExecuteStep() == SQLITE_ROW)
    {
        int get_id = query6.getColumn("id");
        string get_name = query6.getColumn("name");
        string get_mail = query6.getColumn("email");
        int get_year = query6.getColumn("year");

        cout << "id: " << get_id << ", name: " << get_name << ", email: " << get_mail << ", year: " << get_year << endl;
    }
}

CodePudding user response:

In srh_nm you have the name the user entered. (BTW, please use proper variable names. srh_nm is completely unreadable. Why not student_name?)

But you want to search for "%". So you need to add "%" to the name.

srh_nm = srh_nm "%";

(or srh_nm = "%";)

CodePudding user response:

It is not really a C problem but a SQLite one. You can use a LIKE in the query:

SQLite::Statement query6 (db, "SELECT * from students WHERE name LIKE ?");

cout << "Enter student name: " << endl;
getchar();
getline(cin, srh_nm);

query6.bind(1, srh_nm   "%");    // just add the % here...
  •  Tags:  
  • c
  • Related