CodeQL documentation

Uncontrolled data in SQL query

ID: cpp/sql-injection
Kind: path-problem
Security severity: 8.8
Severity: error
Precision: high
   - security
   - external/cwe/cwe-089
Query suites:
   - cpp-code-scanning.qls
   - cpp-security-extended.qls
   - cpp-security-and-quality.qls

Click to see the query in the CodeQL repository

The code passes user input as part of a SQL query without escaping special elements. It generates a SQL query using sprintf, with the user-supplied data directly passed as an argument to sprintf. This leaves the code vulnerable to attack by SQL Injection.


Use a library routine to escape characters in the user-supplied string before converting it to SQL.


int main(int argc, char** argv) {
  char *userName = argv[2];
  // BAD
  char query1[1000] = {0};
  sprintf(query1, "SELECT UID FROM USERS where name = \"%s\"", userName);
  // GOOD
  char userNameSql[1000] = {0};
  encodeSqlString(userNameSql, 1000, userName); 
  char query2[1000] = {0};
  sprintf(query2, "SELECT UID FROM USERS where name = \"%s\"", userNameSql);


  • © GitHub, Inc.
  • Terms
  • Privacy