Ibrahima Khalil Ibrahima Khalil - 5 months ago 12
MySQL Question

iterate mysql table in python

I have an array containning some mysql tables and I want to iterate and visualize.
For example but the programm is not working

tab=["spectreH20","spectreH50"]
for features in tab:
sqlf="select * from WHERE table_name like",features
df=sql.read_sql(sqlf,conn)
print df

Answer

You have a few issues.

"select * from WHERE table_name like" isn't a valid SQL query, and sqlf = "select * from WHERE table_name like", features isn't a valid string formatting, so sqlf ends up being a tuple.

In an ideal world you would use a parameterized query (or "prepared statement"), but these don't work for the FROM clause.

As a compromise, you can simply use string formatting:

 tab=["spectreH20", "spectreH50"]   
 for features in tab:
     sqlf = "select * from {}".format(features)                         
     df = sql.read_sql(sqlf,conn)
     print df

But be aware that this method is exposed to SQL injection and shouldn't be used in general (depends if you trust the source from which features is inputted).

Your best option is to simply hardcode the queries.

Comments