繁体   English   中英

如何使用SOCI从数据库中获取整行?

[英]How to get a whole row from database using SOCI?

...并将其保存为自定义对象类型? 我正在使用PostgreSQL。 当我把所有东西放在一个文件中时,它就可以了。 但是我想将它分成类文件,就像你在cpp中编写时一样。 当我将代码分成* .h和* .cpp文件时,我遇到了错误。

这是我的文件:

test.h

class MyInt
{
public:
    MyInt();
    MyInt(int i);

    void set(int i);
    int get() const;

private:
    int i_;
};

TEST.CPP

#include "test.h"
#include <soci.h>
#include <postgresql/soci-postgresql.h>

MyInt::MyInt()
{

}

MyInt::MyInt(int i)
{
    this->i_ = i;
}

int MyInt::get() const
{
    return this->i_;
}

void MyInt::set(int i)
{
    this->i_ - i;
}

namespace soci
{
    template <>
    struct type_conversion<MyInt>
    {
        typedef int base_type;

        static void from_base(int i,  soci::indicator ind, MyInt & mi)
        {
            if (ind ==  soci::i_null)
            {
                throw soci_error("Null value not allowed for this type");
            }

            mi.set(i);
        }

        static void to_base(const MyInt & mi, int & i,  soci::indicator & ind)
        {
            i = mi.get();
            ind = soci::i_ok;
        }
    };
}

main.cpp中

#include <iostream>
#include "test.h"

int main(int argc, char **argv)
{

    MyInt i;
    sql.open(soci::postgresql, "dbname=mydb user=postgres password=postgrespass");
    sql << "SELECT count(*) FROM person;", soci::into(i);
    std::cout << "We have " << i.get() << " persons in the database.\n";
    sql.close();

    return 0;
}

我这样编译:

g ++ main_test.cpp test.h test.cpp -o App -lsoci_core -lsoci_postgresql -ldl -lpq -I / usr / local / include / soci -I / usr / include / postgresql

并得到了这些错误:

In file included from /usr/local/include/soci/into-type.h:13:0,
                 from /usr/local/include/soci/blob-exchange.h:12,
                 from /usr/local/include/soci/soci.h:18,
                 from main_test.cpp:3:
/usr/local/include/soci/exchange-traits.h: In instantiation of â€soci::details::exchange_traits<MyInt>’:
/usr/local/include/soci/into.h:29:60:   instantiated from â€soci::details::into_type_ptr soci::into(T&) [with T = MyInt, soci::details::into_type_ptr = soci::details::type_ptr<soci::details::into_type_base>]’
main_test.cpp:29:59:   instantiated from here
/usr/local/include/soci/exchange-traits.h:35:5: error: incomplete type â€soci::details::exchange_traits<MyInt>’ used in nested name specifier

上面的问题已经解决,请看@JohnBandela ANSWER。

专门用于type_conversion的代码

template<>
struct type_conversion<MyInt>

需要在test.h中而不是test.cpp。 问题是,如果你像现在一样在test.cpp中使用它,那么在使用SOCI的main.cpp中看不到它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM