【发布时间】:2014-01-05 16:18:30
【问题描述】:
所以我正在对某人的课程进行代码审查,将我们程序的输出转储到数据库中。所以他们得到了一个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 个),这似乎更明智。我错了吗?
【问题讨论】:
-
性能有区别吗?如果 SQLBindParameter 是一项昂贵的操作,那可能是一个原因。
-
@mungflesh shrug 我正在进行静态代码审查,这导致有 50 多个成员变量似乎是个问题。看起来选项是做他当前正在做的事情,在运行时使用 SQLPutData 填充字段,或者每次都重置绑定。
标签: c++ odbc sqlbindparameter