Quoting sql queries with the DB-API

S

snacktime

I'm used to using the perl DBI and not very familiar with the python
DB-API. I am using PyGreSQL. My question is what is the standard way
to quote strings in sql queries? I didn't see any quoting functions
in the DB-API docs. Is quoting handled internally by the PyGreSQL
module?

Also, is this a good way to use variables in an insert/update
statement, or is there a better way?

sql = "insert into test(a,b) values('%s','%s')" % (a,b)
cursor.execute(sql)


Chris
 
L

Leif K-Brooks

snacktime said:
I'm used to using the perl DBI and not very familiar with the python
DB-API. I am using PyGreSQL. My question is what is the standard way
to quote strings in sql queries? I didn't see any quoting functions
in the DB-API docs. Is quoting handled internally by the PyGreSQL
module?

Also, is this a good way to use variables in an insert/update
statement, or is there a better way?

sql = "insert into test(a,b) values('%s','%s')" % (a,b)
cursor.execute(sql)

If you do it like this:

sql = "INSERT INTO test(a, b) VALUES(%s, %s)" # no quotes around the %s
cursor.execute(sql, (a, b))

Then the quoting will be handled automatically for you.
 
S

snacktime

Also, is this a good way to use variables in an insert/update
If you do it like this:

sql = "INSERT INTO test(a, b) VALUES(%s, %s)" # no quotes around the %s
cursor.execute(sql, (a, b))

Then the quoting will be handled automatically for you.

Ah makes sense, thanks for the tip that was exactly what I needed.

Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top