所以我正在对某人的类进行代码审查,将我们程序的输出转储到数据库中。所以他们得到了一个struct Foo
包含一堆成员的列表。现在,他们的类中有一个成员变量,并且在每次调用时复制值,而不是更改 SQLBindParameter 表。
struct Foo
{
int bar;
int baz;
};
class SQLWriter
{
public:
SQLWriter()
{
//initializes SQLHSTMT hQuery to something that takes two ? inputs
SQLBindParameter(hQuery,0,SQL_PARAM_INPUT,SQL_C_INT, 0, 0, &bar_, 0, NULL);
SQLBindParameter(hQuery,1,SQL_PARAM_INPUT,SQL_C_INT, 0, 0, &baz_, 0, NULL);
}
void WriteFoos(const std::vector<Foo> foos)
{
for (int i = 0; i < foos.size(); i++)
{
const Foo& foo = foos[i];
bar_ = foo.bar;
baz_ = foo.baz;
SQLExecute(hQuery);
}
}
private:
SQLHSTMT hQuery; int bar_; int baz_;
};
这似乎......对我来说很疯狂,但老实说我不知道数据库的东西,我只是一个 C++ 程序。在我看来,正确的做法是:
struct Foo
{
int bar;
int baz;
};
class SQLWriter
{
public:
SQLWriter()
{
//initializes SQLHSTMT hQuery to something that takes two ? inputs
}
void WriteFoos(const std::vector<Foo> foos)
{
for (int i = 0; i < foos.size(); i++)
{
const Foo& foo = foos[i];
SQLBindParameter(hQuery,0,SQL_PARAM_INPUT,SQL_C_INT, 0, 0, &foo.bar, 0, NULL);
SQLBindParameter(hQuery,1,SQL_PARAM_INPUT,SQL_C_INT, 0, 0, &foo.baz, 0, NULL);
SQLExecute(hQuery);
}
}
private:
SQLHSTMT hQuery;
};
这样, write 调用就没有那些奇怪的副作用和所有多余的变量。由于 foo 确实有更多的变量(10 个),这似乎更明智。我在这里错了吗?