首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用SOCI从数据库中获取整行?

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

Stack Overflow用户
提问于 2012-11-29 19:51:25
回答 1查看 627关注 0票数 0

..。并将其保存到自定义对象类型中?我在用PostgreSQL。当我把所有东西都放在一个文件里时,它就能工作了。但是我想把它分割成类文件,就像你在cpp中写的时候一样。当我将代码划分为*.h和*.cpp文件时,我会收到错误。

这是我的档案:

test.h

代码语言:javascript
复制
class MyInt
{
public:
    MyInt();
    MyInt(int i);

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

private:
    int i_;
};

test.cpp

代码语言:javascript
复制
#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

代码语言:javascript
复制
#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/include/soci -I /usr/-lsoci_core/postgresql

得到了这些错误:

代码语言:javascript
复制
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的答案。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-29 20:34:12

专门处理type_conversion的代码

代码语言:javascript
复制
template<>
struct type_conversion<MyInt>

需要测试,而不是test.cpp。问题是,如果您像现在一样在test.cpp中使用它,那么它在您使用SOCI的main.cpp中是不可见的。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13633580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档