0

I made a postrgesql database on heroku. Then I tried to access it via a python script. For that I wrote the following code.

import psycopg2

#connect to the db 
con = psycopg2.connect(
            host = "an_aws_ec2_instance",
            database="d57kjtuarj5li8",
            user = "mmpywqodjzxlzr",
            password = "************************************")

#cursor 
cur = con.cursor()

#execute query
cur.execute("CREATE TABLE accounts (user_id serial PRIMARY KEY, username VARCHAR ( 50 ) UNIQUE NOT NULL, password VARCHAR ( 50 ) NOT NULL, email VARCHAR ( 255 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL, last_login TIMESTAMP)")
cur.execute = ("""SELECT * FROM accounts""")
rows = cur.fetchall()

for r in rows:
    print (r)

#commit the transcation 
con.commit()

#close the cursor
cur.close()

#close the connection
con.close()

But on executing the code, I got the following error.

---> 15 cur.execute = ("""SELECT * FROM accounts""")
     16 rows = cur.fetchall()

AttributeError: 'psycopg2.extensions.cursor' object attribute 'execute' is read-only
0

1 Answer 1

1

When you comapare your two SQL lines, there is a major difference.

This calls the method execute on the object cur, with the SQL statement as parameter:

cur.execute("CREATE TABLE accounts (user_id serial PRIMARY KEY, username VARCHAR ( 50 ) UNIQUE NOT NULL, password VARCHAR ( 50 ) NOT NULL, email VARCHAR ( 255 ) UNIQUE NOT NULL, created_on TIMESTAMP NOT NULL, last_login TIMESTAMP)")

This here is something different. Here you are trying to assign a string (the SQL statement) to an attribute (execute), which is read-only on that object.

cur.execute = ("""SELECT * FROM accounts""")
#          THIS  

if remove the = from the second statement, you're fine.

Sign up to request clarification or add additional context in comments.

Comments

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.