Does calling query() on a container prevent SQL Injection?
What reported there for db_query() is still valid for the method that you should use. In short, use placeholders when building the query, instead of concatenating the query string with unsafe input (e.g. the input obtained from from the user).

In Drupal 8 procedural code, you would use \Drupal::database()-&gt;query() instead of db_query(), but you would still avoid using code similar to the following one.

$count = \Drupal::database()-&gt;query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = '. $_GET['user'])-&gt;fetchField();


The correct code would be the following one.

$count = \Drupal::database()-&gt;query('SELECT COUNT(DISTINCT foo) FROM {table} t WHERE t.name = :name', [':name' =&gt; $_GET['user']])-&gt;fetchField();