Skip to content
Advertisement

How to put db name into query using %s

I have a following sql query:

SELECT *
FROM %s.tableA             

The tableA is in db-jablonec so I need to call db-jablonec.tableA.

I use this method in Python:

def my_method(self, expedice):

   self.cursor = self.connection.cursor()

   query = """
   SELECT *
   FROM %s.tableA    
   """

   self.cursor.execute(query, [expedice])
   df = pd.DataFrame(self.cursor.fetchall())

I call it like this:

expedice = ["db-jablonec"]
for exp in expedice:
    df = db.my_method(exp)

But I got an error MySQLdb.ProgrammingError: (1146, "Table ''db-jablonec'.tableA' doesn't exist") Obviously, I want to call 'db-jablonec.tableA' not ''db-jablonec'.tableA'. How can I fix it please?

Advertisement

Answer

It is passing %s as its own string including the quotes ''

you therefore need to pass it as one variable. Concatenate .table to the variable itself then pass it in.

Your query will therefore then be

query = """
   SELECT *
   FROM %s    
   """
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement