473,406 Members | 2,336 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

SQL Query via python

I'm attempting to pass an SQL query via the console:

$ ./getbd month 05

The arguments get seem to passed correctly (via print statements) and then:

cursor.execute ("""
SELECT name, month, day ,category, city FROM bday
WHERE %s = %s
""",(arg1,arg2))

No results. However, if I hardcode the WHERE argument with a field name:

cursor.execute ("""
SELECT name, month, day ,category, city FROM bday
WHERE month = %s
""",(arg2))

It works.

How can I code the left side of the WHERE clause so I can pass an arbitrary
field name to search on?
Thanks,

Jeff Elkins
Jul 19 '05 #1
6 10736
On Fri, 20 May 2005 23:57:01 -0400, Jeff Elkins
<je********@earthlink.net> declaimed the following in comp.lang.python:

The arguments get seem to passed correctly (via print statements) and then:

cursor.execute ("""
SELECT name, month, day ,category, city FROM bday
WHERE %s = %s
""",(arg1,arg2))
You have to remember that .execute(), using the (template,
(arg...)) format, is designed to apply suitable quoting to the
arguments. It does not parse the SQL to determine if arguments are being
used as identifiers and not data values.

The above sample probably generated:

SELECT name, month, day, category, city from bday
WHERE "month" = 5

note the " around month . Obviously, a string /value/ of "month" will
never match a numeric value of 5.

Basically, in any SQL where you are templating /identifiers/
(field names, table names, etc.), you'll need to do /that/ replacement
with Python's % operator. THEN let .execute() quote/substitute the
remaining /data/ values. As others have mentioned though, you'll need to
pre-validate the identifiers if they are coming from user input, to
ensure that someone didn't give you something that is executable SQL and
damaging to the data.

In your example, something like:

validFields = [ "name", "month", "day", "category", "city"]
if arg1.lower() in validFields:
sql = """select .... where %s = %%s""" % arg1.lower()
c.execute(sql, (arg2,))
else:
print "Invalid selection criteria: '%s'" % arg1
print "not found in: %s" % ", ".join(validFields)

-- ================================================== ============ <
wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG <
wu******@dm.net | Bestiaria Support Staff <
================================================== ============ <
Home Page: <http://www.dm.net/~wulfraed/> <
Overflow Page: <http://wlfraed.home.netcom.com/> <

Jul 19 '05 #2
On Saturday 21 May 2005 01:32 pm, Dennis Lee Bieber wrote:
On Fri, 20 May 2005 23:57:01 -0400, Jeff Elkins You have to remember that .execute(), using the (template,
(arg...)) format, is designed to apply suitable quoting to the
arguments. It does not parse the SQL to determine if arguments are being
used as identifiers and not data values.

The above sample probably generated:

SELECT name, month, day, category, city from bday
WHERE "month" = 5


This is getting much clearer. Thanks much.

Jeff
Jul 19 '05 #3
Just as an fyi:

In one weekend I have gone from knowing zip about SQL/Python to implementing
code on my personal server that emails info to family about birthdays and
such. I know I could have installed other *nix programs that would do the
same thing, but so what :)

Thanks so much to the folks on this list who took the trouble to reply. I hope
I can pay it forward in the future.

Jeff Elkins

Jul 19 '05 #4
How about:

cursor.execute("""
SELECT name, month, day ,category, city FROM bday
WHERE %(col_name)s = %%s
""" % dict(col_name=arg1),
(arg2)
)

The "%(col_name)s" will be replaced by normal Python string
substitution, while the "%%s" will be quoted by the db module.

Watch out for SQL injection in arg1, though! Maybe check beforehand that
it is a string containing only word characters...

Jeff Elkins wrote:
I'm attempting to pass an SQL query via the console:

$ ./getbd month 05

The arguments get seem to passed correctly (via print statements) and then:

cursor.execute ("""
SELECT name, month, day ,category, city FROM bday
WHERE %s = %s
""",(arg1,arg2))

No results. However, if I hardcode the WHERE argument with a field name:

cursor.execute ("""
SELECT name, month, day ,category, city FROM bday
WHERE month = %s
""",(arg2))

It works.

How can I code the left side of the WHERE clause so I can pass an arbitrary
field name to search on?
Thanks,

Jeff Elkins

Jul 19 '05 #5
On Mon, May 23, 2005 at 04:12:31PM +0000, Austyn Bontrager wrote:
How about:

cursor.execute("""
SELECT name, month, day ,category, city FROM bday
WHERE %(col_name)s = %%s
""" % dict(col_name=arg1),
(arg2)
)

The "%(col_name)s" will be replaced by normal Python string
substitution, while the "%%s" will be quoted by the db module.

Watch out for SQL injection in arg1, though! Maybe check beforehand that
it is a string containing only word characters...


Maybe what you really need is the ability to search for two fields, or
both fields?

Here's an approach that I usually use:

- Write a search function accepting the parameters you search for.
- If you fill one of the parameters with None (in SQL: NULL), you don't
care for its value
- This way, you can narrow your search as much as you like

Here's a quick test script, using pysqlite2 to demonstrate the approach.
It's also not meant as production code, but at least it only works with
SQL parameter binding.

- SQLite uses :name for named parameters instead of %(name)s.
- locals() is a neat hack to access the local variables as a dictionary

#v+
from pysqlite2 import dbapi2 as sqlite

con = sqlite.connect(":memory:")
cur = con.cursor()
cur.execute("create table test(a, b)")
cur.execute("insert into test(a, b) values (1, 2)")
cur.execute("insert into test(a, b) values (1, 3)")
cur.execute("insert into test(a, b) values (2, 3)")

def search(a, b):
global cur
cur.execute("""
select a, b from test
where (:a is null or a=:a)
and (:b is null or b=:b)
""", locals())
return cur.fetchall()

print search(2, None)
print "-" * 50
print search(None, 3)
print "-" * 50
print search(2, 3)
#v-

-- Gerhard
--
Gerhard Häring - gh@ghaering.de - Python, web & database development

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFCkgXkdIO4ozGCH14RArjUAJsHgGZ9vVRFgTxB4ocv9e 3+Jya5ZACePYa6
R6fjarUVA5P99/UUBnqgTdo=
=9SOq
-----END PGP SIGNATURE-----

Jul 19 '05 #6

"Jeff Elkins" <je********@earthlink.net> wrote in message
news:ma*************************************@pytho n.org...
Just as an fyi:

In one weekend I have gone from knowing zip about SQL/Python to implementing code on my personal server that emails info to family about birthdays and
such.


Actually - http://www.pythonweb.org/ will handle the SQL (and many other
tasks) in a much simpler way!

If you do try the web.database.object examples, be aware that the docs are
not entirely tracking the code; f.ex. databases have no "type" parameter;
it's an "adapter"

i.e.
connection = web.database.connect(type="sqlite",database="objec t-simple.db")
should be:
connection =
web.database.connect(adapter="sqlite",database="ob ject-simple.db")'

there are probably others - it's good to see what the parameters are in
"idle" if something does not work as advertised.

Overall, Pythonweb is very impressive work IMO.


Jul 19 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Sheila King | last post by:
I have searched for an answer to this question on the comp.lang.python archives at Google Groups, and also looked through the (sparse) MySQLdb documentation, and cannot confirm for a FACT what I...
4
by: David Bear | last post by:
How does one query the python environment, ie pythonhome, pythonpath, etc. also, are there any HOWTO's on keeping multiple versions of python happy?
2
by: sumi | last post by:
I am very new to python , I have small query could some one help me. every time I get a new load i need to do few things like creating some dir, changing some file contents and moving some files ,...
3
by: krystoffff | last post by:
Hi I would like to paginate the results of a query on several pages. So I use a query with a limit X offset Y to display X results on a page, ok. But for the first page, I need to run the...
7
by: Bernard Lebel | last post by:
Hello, I'm stumbled at a serious problem, and quite frankly getting desparate. This is a rather long-winded one so I'll try to get straight to the point. I have this Python program, that...
6
by: Caleb Hattingh | last post by:
Hi everyone I suspect this has come up before, but google and group searches for "python package index query" or "pypi query" and the like haven't turned anything up. I want to monitor the...
4
by: Per | last post by:
I am doing a Natural Language processing project for academic use, I think google's rich retrieval information and query-segment might be of help, I downloaded google api, but there is query...
1
by: artistlikeu | last post by:
dear all i am using postgresql data base.... is it possible to write a subquery in inside the main query in python program.... for example something like this..... courses = db.query("select...
17
by: erikcw | last post by:
Hi all, I'm trying to run the following query: amember_db = MySQLdb.connect(host="localhost", user="**********", passwd="*****", db="*******") # create a cursor self.amember_cursor =...
6
by: ApoorvaDesai | last post by:
just for info I am using BOA constructor and python 2.3 I am writting a query which works if i break it up as follows (and it also works if I run it in SQL view of access) stn_name = whatever...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.