Take the 2-minute tour ×

Fairly new to sqlite (and sql). I have several tables I need to generate with several column names, which can change as I code (in c++). How do I manage them? Am I doing it right? There must be utility codes out there that's much better.

Edit: Specifically, I'd like to avoid run-time errors by having an abstraction of the table and field names at compile time (e.g. using #defines, but maybe something else is better).

E.g. I'm currently thinking about creating a class TableHandler that will:

sqlite *db; 
TableHandler tb("TableName");
tb.addField("FirstName", "TEXT");
tb.addField("Id", "INTEGER");

tb.createTable(db); //calls sqlite3_exec("create table TableName(FirstName TEXT, Id INTEGER)");

tb.setEntry("FirstName", "bob");
tb.addEntry(); //calls sqlite3_exec("insert ...");

//this will generate
#define kTableName "TableName"
#define kFirstName "FirstName"
#define kId "Id"
...anything else useful?
share|improve this question
What do you mean by share code? Is there a reason you are not writing a CREATE TABLE statement? –  mikerobi Nov 3 '11 at 20:05
I'd like to have an abstract so that I can easily adjust the tables as I need to grow them (or even rename the table or fields). E.g. tb.setEntry("FirstOppsName", "bob"); //field does not exist. How do i prevent such problems in compile time? tb.setEntry(kFirstName, "bob"); //this is one solution. –  jobobo Nov 3 '11 at 22:41
add comment

1 Answer

I asked a similar question and it was down voted so i deleted it. I wrote some code to do the insert if you are interested. But i agreed with the negative comments that static SQL statements are less error prone. Not to mention less cpu intensive.

For insert i took a std::set of std::pair of std::string. The first string being the column name and the second string its value. And the Query returned a similar structure. I played with std::map and std::vector and std::unordered_set all of them would have different benefits here.

What would be great if you get around to it is a small utility program that could read a definition of a class and write all the SQL for you. I started this and gave up because of parsing the C++ header file got way to complicated for the time I would save on future projects.


std::string Insert(std::string table, std::vector< std::pair<std::string,std::string> >  row)
  if (row.size()==0 || table.size()==0) 
    return "";

    std::stringstream name,value;
    auto it = row.begin();
    name << "INSERT INTO " <<  table.c_str()<<"('" << (*it).first << "'";
    value << "VALUES('" <<(*it).second << "'";  

  for ( ; it < row.end(); it++)
        name << ", '" << (*it).first << "'";
        value << ", '" <<(*it).second << "'";

    name <<  ") ";
    value << ");";
    name << value.str();

    return name.str(); 
share|improve this answer
Added Insert code as an Example –  Joe McGrath Nov 11 '11 at 16:35
add comment

Your Answer


