Solved

Syntax for a Variable in a MySQL Query in Python

Posted on 2007-04-07
2
479 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

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Variable is a place holder or reserved memory locations to store any value. Which means whenever we create a variable, indirectly we are reserving some space in the memory. The interpreter assigns or allocates some space in the memory based on the d…
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 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…

828 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