Home > Software engineering >  Python mysql select field based on variable
Python mysql select field based on variable

Time:11-11

I want to create a MySQL syntax to select a field based on a variable, what I have is:

book_category = "science"
mycursor_a.execute(("SELECT {book_categories} FROM research_papers WHERE book_Name = %s", (book,)).format(book_categories = book_category))

but I get the following error:

AttributeError: 'tuple' object has no attribute 'format'

CodePudding user response:

That's because

(book,))

is a tuple and not an object, remember that tuples don't have dynamic reading like an object or dictionary.

To solve that we need a dictionary variable as a result.

can be achieved by setting the cursor.

mycursor_a= db.cursor( buffered=True , dictionary=True)
book_category = "science"
mycursor_a.execute(("SELECT {book_categories} FROM research_papers WHERE book_Name = %s", (book,)).format(book_categories = book_category))

CodePudding user response:

Hi the reason it is not working becuase


("SELECT {book_categories} FROM research_papers WHERE book_Name = %s", (book,))

is considered as tuple (instead of string) and to avoid that you can use book same as you used book_categories

so here is my proposed solution to your value

book_category = "science"
book = "your value"
mycursor_a.execute("SELECT {book_categories} FROM research_papers WHERE book_Name = {variable}" ).format(book_categories = book_category ,  variable = book )

  • Related