Home > Software engineering >  Psycopg2 syntax error when using SQL module
Psycopg2 syntax error when using SQL module

Time:01-13

query=SQL(
    "CREATE USER {id} WITH PASSWORD %s".format(
        id=Identifier(id)
    )
)
try:
    self.cur.execute(
        query=query,
        vars=[password]
    )
except DuplicateObject:
    print("{id} User already created.".format(id=id))
else:
    print("{id} User create.".format(id=id))

This is the code to create a user in postgresql.

query=SQL(
    "CREATE USER {id} WITH PASSWORD %s".format(
        id=Identifier(id)
    )
)

ID argument is defined as identifier class.

self.cur.execute(
            query=query,
            vars=[password]
        )

The password argument is defined as a variable of the execution function.

psycopg2.errors.SyntaxError: 오류: 구문 오류, "(" 부근
LINE 1: CREATE USER Identifier('administrator') WITH PASSWORD 'Y2zfW...

When I run the code, I get a syntax error.
Why am I getting a syntax error?

CodePudding user response:

You are calling the wrong .format. This works for me:

query = sql.SQL("CREATE USER {} WITH PASSWORD %s").format(sql.Identifier('falken'));
c.execute(query, ['pencils'])

Notice that I am calling .format on the SQL object, not on the string!

  •  Tags:  
  • Related