jeudi 5 novembre 2020

Creating objects from a retrieved row from Sqlite database

This is a C++11 program that connects to an Sqlite database, using the SqliteModernCpp library. There is the following class, which represents a record from this database (at least, the header file):

#ifndef MOVIE_H
#define MOVIE_H

#include<string>

class movie
{
    public:
        movie(int id, std::string title, int year, int length);
        int get_id() const;
        void set_id(int id);
        std::string get_title() const;
        void set_title(std::string title);
        int get_year() const;
        void set_year(int year);
        int get_length() const;
        void set_length(int length);

    private:
        int id;
        std::string title;
        int year;
        int length;
};

#endif // MOVIE_H

In the main function of the program, the database is queried to retrieve a record, by the "id" field. Note that this field in the database is PK, NN and AI, so there will only be one record retrieved by this query. Currently, it just prints the data to the console using a lambda. How to return an object of type movie with this query?

int main()
{
    // connect to the database
    sqlite::database db("database.db");

    // retrieve a record by ID
    auto id = 1;
    db << "SELECT * FROM movies WHERE rowid = " + std::to_string(id) >> [&](int rowid, std::string title, int year, int length)
    {
        std::cout << title;
    };

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire