Home > Back-end >  How to put db name into query using %s
How to put db name into query using %s

Time:09-06

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?

CodePudding user response:

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    
   """

CodePudding user response:

I think this will helpful for you

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%%'

Refer This.

  • Related