问题
To create a user through psycopg2, I am using the following code :
cur=conn.cursor()
cur.execute("create user %s with password %s",('abcdefgh','0h/9warrAttrgd8EF0gkvQ==',))
This gives the following error :
syntax error at or near "'abcdefgh'" LINE 1: create user 'abcdefgh' with password '0h/9warrAttrgd8EF0gkvQ.
It seems that %s is placing quotes around the username, which postgres doesn't like while creating a user. The following code works fine :
cur.execute("create user abcdefgh with password %s",('0h/9warrAttrgd8EF0gkvQ==',))
Any workaround for this ?
回答1:
Use psycopg2.extensions.AsIs(object):
from psycopg2.extensions import AsIs
cur.execute("create user %s with password %s", (AsIs('abcdefgh'), '0h/9warrAttrgd8EF0gkvQ==',))
来源:https://stackoverflow.com/questions/53022587/postgres-psycopg2-create-user