Note that there are some explanatory texts on larger screens.

plurals
  1. POPython, MySQLdb and escaping table names?
    primarykey
    data
    text
    <p>I may be missing something obvious, but I can't figure out how my code is different from various examples I see in the online documentation for MySQLdb.</p> <p>I'm fairly new to programming python, more experienced with perl. What I'm trying to do is get into certain good habits early on (like in perl I always start with 'use strict; use warnings'), so I'm trying to ensure I create re-usable functions in an independent file (funct.py) to save me time later on down the line.</p> <p>I've got this function for selecting random rows from a table:</p> <pre><code>def returnRandom(conn,countcol,table,field): cursor = conn.cursor() cursor.execute('SELECT MAX(%s) FROM %s',(countcol,table)) maxRow = cursor.fetchone()[0] cursor.execute("SELECT MIN(%s) FROM %s",(countcol,table)) minRow = cursor.fetchone()[0] randomId = random.randrange(minRow,maxRow+1,1) cursor.execute("SELECT ? FROM ? WHERE id &gt;=? LIMIT 1",field,table,randomId) return cursor.fetchone()[0] </code></pre> <p>It's being called like this:</p> <pre><code>msg = funct.returnRandom(conn,"id","testtable","data") </code></pre> <p>Unfortunately it errors out with: _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''testtable'' at line 1")</p> <p>If I put testtable in in place of the %s on the execute line, The query will run but it looks like it runs</p> <pre><code>SELECT MAX('id') FROM testtable; </code></pre> <p>which of course returns 'id'.</p> <p>Given both of those it looks like it's quoting the %s entries when it tries to execute them. I was wondering if anyone could explain how I get it to stop doing that, or how I should actually being doing what I'm trying to achieve? I want the function to be as generic as possible, so relying on data being passed to it by when it's called.</p> <p>edit: I should add, if I substitute in ? marks:</p> <pre><code>.... cursor.execute('SELECT MAX(?) FROM ?',(countcol,table)) File "/usr/lib/pymodules/python2.7/MySQLdb/cursors.py", line 151, in execute query = query % db.literal(args) TypeError: not all arguments converted during string formatting </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload