2

所以我正在对某人的类进行代码审查,将我们程序的输出转储到数据库中。所以他们得到了一个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 个),这似乎更明智。我在这里错了吗?

4

1 回答 1

0

SQLBindParameter() 的部分优点或用处在于您可以绑定到缓冲区,并且只需在每个 SQLExecute() 之前更改缓冲区。

虽然按照您在第一个代码片段中显示的方式执行此操作可能有点难看,但每次重新绑定可能会非常昂贵,具体取决于它发生的次数。

Mungflesh 提出了一个很好的观点,我同意与代码看起来的干净程度相比,性能可能会成为一个更大的问题。

您可能仍然能够找到清理代码的方法,但请记住,如果没有必要,您最好避免重新绑定。

于 2014-08-21T14:57:19.760 回答