skip to Main Content

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'

2

Answers


  1. 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))
    
    Login or Signup to reply.
  2. 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 )
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search