Solved

Syntax for a Variable in a MySQL Query in Python

Posted on 2007-04-07
2
473 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
2 Comments
 
LVL 14

Accepted Solution

by:
RichieHindle earned 250 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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

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

Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

786 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