Reputation: 303
I am trying to fetch all the rows from the MySQL DB in Python. How to fetch all row from the table, when the table name is variable?
Here is a method that I wrote, however I am getting error while running it.
def get_rows(self, table_name):
cursor = self.conn.cursor()
query = ("SELECT * "
"FROM %s ")
try:
cursor.execute(query, (table_name,))
value = cursor.fetchall()
finally:
cursor.close()
return value
And I am getting the following error:
AttributeError: 'NoneType' object has no attribute 'cursor'
I tried the similar way in WHERE
clause and it worked fine.
Upvotes: 1
Views: 2831
Reputation: 631
You have a problem with conn object.
'NoneType' object has no attribute 'cursor' means conn is None, probably because it wasn't established during the __ init __ call.
Upvotes: 2
Reputation: 311863
You can't dynamically bind object names (here you're attempting to bind a table name) or syntactic constructs to a query. If you wish to have such a behavior you'd have to resort to string manipulation, meaning you're forfeiting all the security advantages prepared statements offer:
query = ("SELECT * FROM %s" % table_name)
try:
cursor.execute(query, ())
Upvotes: 1