0

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 2

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.