September 2010
Intermediate to advanced
440 pages
9h 23m
English
As we have seen in previous chapters, processing a SELECT query in Python is as simple as execute() and fetchall(). However, Python also allows us to build statements dynamically, and this applies to joins, unions, and subqueries as well.
If we want column from table1, but the column reference for the subquery is colref, from both table1 and table2, we can write the following:
#!/usr/bin/env python import MySQLdb mydb = MySQLdb.connect('localhost', 'skipper', 'secret', 'sakila') cursor = mydb.cursor() table1 = 'film' table2 = 'film_actor' column = 'film_id, title' colref = 'film_id' statement = "SELECT %s FROM %s WHERE %s IN (SELECT %s FROM %s)" %(column, table1, colref, colref, table2) cursor.execute(statement) results ...Read now
Unlock full access