gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:27:08 24 4
gpt4 key购买 nike

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

这是我的文件:

测试.h

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

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

private:
int i_;
};

测试.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 的回答。

最佳答案

你专攻 type_conversion 的代码

template<>
struct type_conversion<MyInt>

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

关于c++ - 如何使用 SOCI 从数据库中获取整行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13633580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com