Click here to Skip to main content
15,065,328 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I need help modifying the function below. My assignment is to prevent SQL injection in C++. I figured out the best approach is to use regular expressions and regex to solve it but not sure how to implement it into the code. I'm supposed to flag "=" and possibly use regex_search() to search for " or = ".

This is the function:

bool run_query(sqlite3* db, const std::string& sql, std::vector< user_record >& records)
// TODO: Fix this method to fail and display an error if there is a suspected SQL Injection
// NOTE: You cannot just flag 1=1 as an error, since 2=2 will work just as well. You need
// something more generic

// clear any prior results

char* error_message;
if(sqlite3_exec(db, sql.c_str(), callback, &records, &error_message) != SQLITE_OK)
std::cout << "Data failed to be queried from USERS table. ERROR = " << error_message << std::endl;
return false;

return true;

What I have tried:

I have tried to find resources on using regex inc++ but can't find anything to directly help with this assignment.
Updated 29-Mar-21 1:13am
Mohibur Rashid 28-Mar-21 17:50pm
have you looked up PCRE?

If you use binding, sqlite3 provided method is sufficient for protecting from SQL injection.
Richard Deeming 29-Mar-21 6:47am
Simple answer: Don't.

Trying to filter out "bad" characters from your values will lead to your code rejecting valid values, and potentially letting bad ones through.

The way to prevent SQLi is simple: always use a properly parameterized query. No exceptions.
Dave Kreskowiak 29-Mar-21 11:57am
Bad idea. There are perfectly valid reasons for a real query to use '' or = ''.

1 solution

Regular Expressions are a good tool - but only when used for what they are good at.
And using a Regex to prevent SQL Injection is the wrong approach. Instead use Parameterised queries at all times and the problems just goes away.
Simple, and foolproof - provided you don't "forget" and miss one bit of string concatenation!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900