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

时间:2012-11-29 19:51:25

标签: c++ postgresql postgresql-9.1 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。

1 个答案:

答案 0 :(得分:2)

专门针对type_conversion的代码

template<>
struct type_conversion<MyInt>

需要在test.h中而不是test.cpp。问题是如果你在test.cpp中有它,就像你现在一样,它在你使用SOCI的main.cpp中是不可见的