I've been trying to find a postgres interface for python 2.x that supports real prepared statements, but can't seem to find anything. I don't want one that just escapes quotes in the params you pass in and then interpolates them into the query before 开发者_JS百科executing it. Anyone have any suggestions?
Either py-postgresql for Python3 or pg_proboscis for Python2 will do this.
Python-pgsql will also do this but is not threadsafe. Notably, SQLAlchemy does not make use of prepared statements.
have a look at web.py's db module
examples can be found at
- http://webpy.org/cookbook/select
- http://webpy.org/cookbook/update
- http://webpy.org/cookbook/delete
- http://webpy.org/Insert
These links hint at the answer when using psycopg2. You don't need special API extensions.
- Re: psycopg2 and prepared statements
- Prepared Statements in Postgresql
- Transparently execute SQL queries as prepared statements with
Postgresql (Python recipe)
Here's an example that I played with. A word of caution though, it didn't give me the expected performance increase I had hoped for. In fact, it was even slower (just slightly) in a contrived case where I tried to read the whole table of one million rows, one row at a time.
cur.execute('''
PREPARE prepared_select(text, int) AS
SELECT * FROM test
WHERE (name = $1 and rowid > $2) or name > $1
ORDER BY name, rowid
LIMIT 1
''')
name = ''
rowid = 0
cur.execute('EXECUTE prepared_select(%s, %s)', (name, rowid))
精彩评论