Escaping SQL in python
Steve Holden
sholden at holdenweb.com
Wed Jun 27 09:45:45 EDT 2001
The *best* way to handle this is to use dynamic SQL, and let the module do
the quoting.
For example:
conn = some_db_module.connect(args)
cursor = conn.cursor()
data = ("O'Brian", "Seamus")
sql = """INSERT INTO my_table (LastName, FirstName) VALUES (?, ?)"""
cursor.execute(sql, data)
The question marks are parameter markers, and they are replaced in the
executed SQL statement by successive elements of the data tuple provided as
the second argument to cursor.execute().
Beware, though. There are five different parameter styles, so the style you
have to use might depend on the engine you are using. Hopefully this will be
enough to enlighten you on a further reading of the DB API documentation.
regards
Steve
--
http://www.holdenweb.com/
"Erno Kuusela" <erno-news at erno.iki.fi> wrote in message
news:kuoframchq.fsf at lasipalatsi.fi...
> In article <3B39A1B8.A7FCE4C7 at kvarteret.uib.no>, Kjetil Nygård
> <kjetiln at kvarteret.uib.no> writes:
>
> | Is there a method to escape ' " \ and the like in python auto-magiacaly
> | ?
>
> it is not portable between different sql dialects, so there is no
> generic way. the database-specific modules can provide such a function,
> but it is usually easy to write one yourself.
>
> -- erno
More information about the Python-list
mailing list