evtl. bin ich zu blöd Dokus zu lesen; ich versichere aber, dass ich das heute schon gefühlte 100x getan habe und trotzdem nicht dahinter komme
Im psycopg - Usage Guide steht:
Ich habe mir jetzt ein stupid-as-f**k Beispiel gebaut:Psycopg can automatically convert Python objects to and from SQL literals: using this feature your code will be more robust and reliable.
>>> SQL = "INSERT INTO authors (name) VALUES (%s);"
>>> data = ("O'Reilly", )
>>> cur.execute(SQL, data)
Code: Alles auswählen
#!/usr/bin/python2
import psycopg2
# Create connection and cursor objects
con = psycopg2.connect(database="postgres", user="postgres", host="127.0.0.1", password="postgres")
con.set_isolation_level(0)
cur = con.cursor()
# http://initd.org/psycopg/docs/usage.htm ... ql-queries
SQL = "CREATE DATABASE %s;"
data = ("testdb", )
cur.execute(SQL, data)
con.close
So, jetzt führe ich das aus und erhalte:
Kopiere ich das und gebe das 1:1 in psql ein, sagt der auch:judge@judge-nb:~$ ./test.py
Traceback (most recent call last):
File "./test.py", line 12, in <module>
cur.execute(SQL, data)
psycopg2.ProgrammingError: syntax error at or near "'testdb'"
LINE 1: CREATE DATABASE 'testdb';
Gebe ich es ohne die Anführungsstriche in psql ein, klappt es:postgres=# CREATE DATABASE 'testdb';
ERROR: syntax error at or near "'testdb'"
LINE 1: CREATE DATABASE 'testdb';
postgres=#
Wenig überraschend: Wenn ich das stumpf als unparameterisierte Operation ausführen lasse, klappt es auch mit psycopg2:postgres=# CREATE DATABASE testdb;
CREATE DATABASE
postgres=#
Code: Alles auswählen
SQL = "CREATE DATABASE testdb;"
cur.execute(SQL)
Was macht psycopg2 da? Die zitierte Doku liest sich für mich so, als wenn er mit genau so einer Syntaxunterscheidung umgehen kann.
Oder mache ich was falsch?