[PYTHON] I'm having trouble getting "ERROR: cannot execute ALTER TABLE in a read-only transaction" on heroku

problem

When I try to add a row with heroku's "Heroku Postgres --Add-ons", I get angry with "ERROR: cannot execute ALTER TABLE in a read-only transaction".

sql_test2.png

solution

Create a class to access the Postgres database from python like this.


import os
import psycopg2
import json
import pprint

class PostgreSql:
    def __init__(self):
        self.conn = self.get_connection()
        self.cur  = self.conn.cursor()

    ##############################################
    #DB connection acquisition function
    #
    def get_connection(self):
        dsn = "host=XXXXXXXXXXXXXX\
            port=XXXX \
            dbname=XXXXXXXXXX \
            user=XXXXXXXXX \
            password=XXXXXXXXXXXXXX"
        return psycopg2.connect(dsn)
    
    ##############################################
    #insert function
    #
    def insert(self, sqlStr):
        self.cur.execute('BEGIN')
        self.cur.execute(sqlStr)
        self.cur.execute('COMMIT')

    ##############################################
    #Function for selecting with mysql
    #
    def select(self,  sqlStr):
        self.cur.execute(sqlStr)
        return list(self.cur)

if __name__ == "__main__":

    psql = PostgreSql()

    ##############################################
    #Add column
    #
    sql = "ALTER TABLE tbl_name ADD COLUMN category2 text;"
    psql.insert(sql)

Let's add a column using the insert function of the psql class we created! !!

    sql = "ALTER TABLE tbl_name ADD COLUMN category2 text;"
    psql.insert(sql)

If it is selected and added on heroku's dashboard, it's done !!

sql_test.png

This is how to solve "ERROR: cannot execute ALTER TABLE in a read-only transaction".

Recommended Posts

I'm having trouble getting "ERROR: cannot execute ALTER TABLE in a read-only transaction" on heroku
I'm having trouble getting a Unicode Encode Error on jrnl (Python) on Mac / Marvericks.
A story about a 503 error on Heroku open