title: How to avoid SQL injection with "SELECT * FROM {table_name}"?
body: <p>In Python using Psycopg2 with the following code:</p>
  
  <pre><code>import psycopg2
  
  import getpass
  
  conn = psycopg2.connect("dbname=mydb user=%s" % getpass.getuser())
  cursor = conn.cursor()
  
  tables = ["user", "group", "partner", "product"]
  for table in tables:
  
      # with sql injection
      cursor.execute("SELECT name FROM %s LIMIT 1" % (table,))
      print "table", table, "result", len(cursor.fetchone())
  
      # without sql injection
      cursor.execute("SELECT name FROM %s LIMIT 1", (table,))
      print "table", table, "result", len(cursor.fetchone())
  </code></pre>
  
  <p>The output was:</p>
  
  <pre><code>table res_partner result 1
  Traceback (most recent call last):
    File "my_psycopg2_example.py", line 16, in &lt;module&gt;
      cursor.execute("SELECT name FROM %s LIMIT 1", (table,))
  psycopg2.ProgrammingError: syntax error at or near "'res_partner'"
  LINE 1: SELECT name FROM 'res_partner' LIMIT 1
  </code></pre>
  
  <p>With SQL injection it works fine.</p>
  
  <p>But we don't want to create a security issue.</p>
  
  <p>We read <a href="http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries" rel="nofollow">this documentation</a> and in it found the following comment:</p>
  
  <blockquote>
    <p>Only variable values should be bound via this method: it shouldn’t be used to set table or field names. For these elements, ordinary string formatting should be used before running <code>execute()</code>.</p>
  </blockquote>
  
  <p>But if we use "ordinary string formatting", we'll have SQL injection too.</p>
  
  <p>What's a good way to manage this special case, and avoid SQL injection?</p>