0

I'm trying to update user credentials for PostgreSQL db user using Python. I've tried referring to the following thread but that doesn't seem to solve my issue unfortunately:

How to change password of a newly created user using variable in postgresql 9.5 SP

Here's my code:

con = p.connect(database="mydB", user="abc", password="testing", host="127.0.0.1", port="5432")
cur = con.cursor()

uid = "adi"
pwd = "test6"

statement = statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)

cur.execute( statement)
cur.execute('''COMMIT''')

I get the following error: ProgrammingError: syntax error at or near "'adi'"

Please help or refer me to a thread with a better solution. Thanks in advance, everyone!

error image

5
  • Show us the full error traceback! Commented May 16, 2020 at 3:06
  • @KlausD. edited the question with the complete error! Commented May 16, 2020 at 3:22
  • Your traceback differs from the code. Please post the code that leads to that error. Commented May 16, 2020 at 3:29
  • @KlausD., added the original code - edited my question. Thank you! Commented May 16, 2020 at 3:33
  • @KlausD. I have added my answer here. I was able to solve this. Commented May 16, 2020 at 5:07

2 Answers 2

2

I was able to solve this successfully.

import psycopg2 as p
con = p.connect(database="mydB", user="adi", password="xxxx", host="127.0.0.1", port="5432")
cur = con.cursor()

uid = "adi"
pwd = "test"

statement = '''ALTER USER {} WITH PASSWORD %s '''.format(uid)

cur.execute(statement, [pwd])
cur.execute('''COMMIT''')
Sign up to request clarification or add additional context in comments.

Comments

0

Try to give the username and password in the actual statement and try executing.

First try removing the extra quotation before ALTER USER and execute. If doesn't work try this:

statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE 'ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd)

cur.execute(statement)

1 Comment

Tried the following: statement = '''CREATE or REPLACE FUNCTION add_user ({}, {}) RETURNS void AS $$ EXECUTE ALTER USER ' || $1 || ' WITH PASSWORD || $2||'''.format(uid,pwd) I get the error: ProgrammingError: unterminated dollar-quoted string at or near "$$ EXECUTE ALTER USER ' || $1 || ' WITH PASSWORD || $2||"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.