开发者

Replacing some chars in a string

If I have a variable like:

char *sql;
sql = "insert into Norm1Tab values (?,?,?,?,?,?)";

I would like to replace each ? by values that are stored in other char or char* va开发者_开发技巧riables. How I can do that in C++ ?


In C++ don't use char* C-style strings. If you use std::string you can use find and replace to do what you want.

But please don't do that. You'll just open yourself up to a million SQL injection attacks. Use prepared statements with bound parameters instead.


If you are using sqlite (sure looks like it), you do not have to do the string replaces yourself. Use sqlite3_bind_* instead.

bind documentation

There are a lot of benefits from using the APIs from your database provider, so you really shouldn't avoid them if you can help it. You'll have better type safety, better protection against injection, and way better performance.

Otherwise, I would use boost::format for this.

std::string sql = "insert into Norm1Tab values ('%1%','%2%');";
boost::format fmt(sql);
std::string stmt = boost::str( fmt % param1 % param2 );

As mentioned by others, you'll need to clean your params to make sure there aren't any injection vulnerabilities.

If you don't, anything with special characters could break it.

char const* param1 = "Joe's House";

It would take some knowledge of the structure to destroy it. As soon as someone saw the error message from the Joe's House, they would probably know that they could do worse.

char const* param1 = "'); DROP Norm1Tab; --";

If you do this consistently, it is only a matter of time before a smart person is going to have your full schema. With sqlite for instance, any injection on a query could get you all the information you needed to quietly modify your records in any way that they wanted.

SELECT * FROM sqlite_master;


You could put %s and use sprintf to populate the fields ...

However, for the problem at hand, you probably want a prepared statement ...


If you're adamant about doing it this way (as opposed to using the first comment by Matteo Italia), check the solution found here:

How do I Search/Find and Replace in a standard string?

It's not quite what you need, but it shows how to can use .find() to get the location of the question mark and .replace to replace the question mark with the contents of your character buffers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜