Menu

execute with args doesn't work

Help
2009-02-20
2012-09-19
  • Jonathan Livni

    Jonathan Livni - 2009-02-20

    I don't know why, but a simple execute won't work for me:

    This works: cursor.execute("""select * from table_a""")
    This doesn't: cursor.execute("""select * from %s""",("table_a",))

    I receive the following error:
    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 ''table_a'' at line 1")

    I use Python 2.5.4 and the MySQLdb 1.2.2 in windows and executed the commands in IDLE

    (I'm not sure this is relevant, but notice that table_a has two apostrophes before and two after instead of inverted commas)

    Please help :)

     
    • Andy Dustman

      Andy Dustman - 2009-02-21

      You can't pass table names as parameters. This is true for any DB-API database adapter.

       
    • Jonathan Livni

      Jonathan Livni - 2009-02-21

      Thanks for the quick answers. It worked! I still have a few questions though:

      1) When is it legitimate to use the args and when not?

      2) If can't use the args - I can't use executemany! This forces me to use a loop. Isn't there an alternative?

      3) I've actually executed cursor.execute('ALTER TABLE table_a ADD %s text' % column_name) to create new tables. One of the tables already existed so I received an OperationalError. I tried to capture it (with try\except) but Python couldn't. Why?

      The error: OperationalError: (1060, "Duplicate column name 'column_a'")

      When I tried to capture it: NameError: global name 'OperationalError' is not defined

       
    • DScher

      DScher - 2009-02-21

      Try this:

      cursor.execute('SELECT * FROM %s' % ('table_a'))

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.