如何prepare的SQL查询C ++字符串 [英] How to prepare a C++ string for sql query
问题描述
我不得不prepare串为适合于查询,因为这些字符串将在查询作为字段值被使用。如果包含'等SQL查询无法执行。
I have to prepare strings to be suitable for queries because these strings will be used in the queries as field values. if they contain a ' etc the sql query fails to execute.
我要因此与来代替我已经看到了code找到并用子替换子。但我想这个问题是有点棘手,因为替换字符串还包含两个单引号'替换一个引号',所以当我必须要找到下一个次数,会遇到一个,这是故意所取代。
I therefore want to replace ' with '' I have seen the code to find and replace a substring with a substring. but I guess the problem is a little tricky because replacing string also contains two single quotes '' replacing one quote ' so when I have to find the next occurance it would encounter a ' which was intentionally replaced.
我使用SQL精简版C API和例子查询看起来像这样
I am using Sql lite C api and the example query might look like this
select * from persons where name = 'John' D'oe'
由于李四包含'查询会失败,所以我想的所有出现'之名与''代替
Since John Doe contain a ' the query will fail , so I want all occurances of ' in the name to replaced with ''
任何想法你们$ P $如何ppares查询您的字段值是SQL使用?可能这是一个基本的东西,但我在C / C ++也不是太聪明了。
Any ideas how you guys prepares your field values in query to be used in sql ??? may be it's a basic thing but I am not too smart in C/C++.
您的帮助将是非常有益的。
your help would be very helpful
推荐答案
与争论,而不是替换的东西,这可能导致一些问题(如SQL注入漏洞)使用查询。
Use queries with arguments instead of replacing stuff, which could lead to several problems (like SQL injection vulnerabilities).
MySQL的例子:
sql::Connection *con = ...;
string query = "SELECT * FROM TABLE WHERE ID = ?";
sql::PreparedStatement *prep_stmt = con->prepareStatement(query);
prep_stmt->setInt(1, 1); // Replace first argument with 1
prep_stmt->execute();
这将执行 SELECT * FROM表,其中ID = 1
。
修改:SQLite的$ P $更多信息ppared陈述这里和这里。
EDIT: more info for SQLite prepared statements here and here.
这篇关于如何prepare的SQL查询C ++字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!