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.
-
please some one add solution with prepared statement for securityMahmoud Magdy– Mahmoud Magdy2023年01月19日 07:07:00 +00:00Commented Jan 19, 2023 at 7:07
2 Answers 2
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.
5 Comments
cursor.close() self.conn.close() Could it be because of that?self.conn.close() in it. I called it in the end (after executing all the DB calls). And it worked fine! Thank you :)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, ())
4 Comments
query = "SELECT * FROM %s " % table_name try: cursor.execute(query) Still, no luck.