سؤال

So I'm doing a code review of someone's class that dumps out output of our program to a database. So they are getting a list of struct Foo with a bunch of members. Right now, they have a member variable in their class and are copying the values on each call, and not changing the SQLBindParameter table.

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_;
};

This seems...insane to me, but I honestly don't know database stuff, I'm more just a C++ program. What seems to me to be the right way to do it would be:

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;
};

This way the write call doesn't have those weird side effects and all those excess variables. Since foo really has more variables (10's) this seems alot more sensible. Am I wrong here?

هل كانت مفيدة؟

المحلول

Part of the beauty or usefulness of SQLBindParameter() is that you can bind to a buffer and just change the buffer before each SQLExecute().

Though it may be a bit more ugly to do it the way you show in the first code snippit, re-binding each time could be very costly depending on how many times it occurs.

Mungflesh raises a good point and I agree that performance could become a larger issue for you in comparison to how clean the code looks.

You may still be able to find a way to clean up the code, but keep in mind that you would ideally want to avoid re-binding if it is not necessary to do so.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top