【问题标题】:Creating objects from a retrieved row from Sqlite database从 Sqlite 数据库中检索到的行创建对象
【发布时间】:2021-02-18 02:24:03
【问题描述】:

这是一个使用 SqliteModernCpp 库连接到 Sqlite 数据库的 C++11 程序。有以下类,表示来自该数据库的一条记录(至少是头文件):

#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

在程序的主要功能中,通过“id”字段查询数据库以检索记录。注意数据库中的这个字段是PK、NN和AI,所以这个查询只会检索到一条记录。目前,它只是使用 lambda 将数据打印到控制台。如何使用此查询返回 movie 类型的对象?

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

【问题讨论】:

    标签: c++ sqlite c++11


    【解决方案1】:

    这似乎太容易了,因为您已经解决了困难的部分(未经测试的代码)

    auto id = 1;
    movie idmovie
    db << "SELECT * FROM movies WHERE rowid = " + std::to_string(id) >> [&](int rowid, std::string title, int year, int length)
    {
        idMovie = { rowid, title, year, length };
    };
    

    你可以把它缩短为

    auto id = 1;
    movie idmovie = db << "SELECT * FROM movies WHERE rowid = " + std::to_string(id) >> [&](int rowid, std::string title, int year, int length) -> movie
    {
        return  { rowid, title, year, length };
    };
    

    但我还没有测试其中的错误:)

    【讨论】:

      猜你喜欢
      • 2013-05-25
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      • 2011-09-09
      相关资源
      最近更新 更多