Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Syntax for a Variable in a MySQL Query in Python

Posted on 2007-04-07
2
Medium Priority
?
524 Views
Last Modified: 2007-04-08
In this MySQL query, I want to use a variable for the DocNumber, instead of the hardcoded '99':

    cursor.execute("SELECT DocText FROM compare WHERE DocNumber = '99' ORDER BY Posted ASC limit 1")

I tried this, but it did not work:

   Doc = '99'
. . .
   cursor.execute("SELECT DocText FROM compare WHERE DocNumber = 'Doc' ORDER BY Posted ASC limit 1")

In Python, what is the proper syntax for using a variable inside a double-quoted sql statement in the cursor.execute function?
0
Comment
Question by:Randall-B
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 14

Accepted Solution

by:
RichieHindle earned 1000 total points
ID: 18871800
It looks like this:

cursor.execute("SELECT DocText FROM compare WHERE DocNumber = %s ORDER BY Posted ASC limit 1", (Doc,))

Note that you don't use single quotes around the %s in the query - MySQL takes care of that for you.  To pass multiple values, you'd do something like this:

cursor.execute("SELECT DocText FROM compare WHERE DocNumber = %s OR DocNumber = %s ORDER BY Posted ASC limit 1", (Doc1, Doc2))
0
 

Author Comment

by:Randall-B
ID: 18871818
Yes. That works great. Thanks!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question