Solved

Syntax for a Variable in a MySQL Query in Python

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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
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 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…

707 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now