So I loock at sqlite3cpp wiki. And thay have such a nice API:
sqlite3pp::command cmd(db, "INSERT INTO contacts (name, phone) VALUES (:user, :phone)");
cmd.bind(":user", "Mike");
cmd.bind(":phone", "555-1234");
cmd.execute();
I wonder how using boost to create API alike it forregular std::string? meaning something like
std::string str = "INSERT INTO contacts (name, phone) VALUES (:user, :phone)";
bind(str, ":user", "Mike");
bind(str, ":phone", "555-1234");
Is it possible to create such thing with boost and how to do it?
Replacing a string is easy, but to perform something that is type-safe and will convert the SQL nicely, is slightly different. We need a binder class that can bind by the type passed and do any necessary conversions.
Firstly, we need to wrap up
std::type_infoso that it can be used in a hash map:Next, we need the class itself. I’m using C++11 here, so I’m going to use lambdas. For each type we register, we’ll register a function that takes a string and returns it in a format suitable for SQL. In this example, I register one for a string and one for an int. The string one just replaces
'with''and returns it in quotes itself. The int one just returns itself, no parsing to do for SQL.And as you can see, we have the bind function.
Now we can bind in a type-safe way!
EDIT: fixed some errors.