1

I'm trying to create a Postgres table using psycopg2 in Python as follows:

import psycopg2

class DbOperations (object):

def __init__(self):

    self.dummy = None
    self.conn = None
    self.cur = None
    self.query = None
    self.db_name = "alarm_log"
    self.table_name = "alarms"
    self.user = "cayman"
    self.password = "admin"
    self.host = "127.0.0.1"

def db_connect(self):

    self.conn = psycopg2.connect(dbname=self.db_name, user=self.user, password=self.password, host=self.host)
    self.cur = self.conn.cursor()

def db_disconnect(self):

    self.conn.close()

def db_create_table(self):

    self.query ="""
                CREATE TABLE COMPANY(
           ID INT PRIMARY KEY     NOT NULL,
           NAME           TEXT    NOT NULL,
           AGE            INT     NOT NULL,
           ADDRESS        CHAR(50),
           SALARY         REAL
        );
    """
    print (self.query)
    self.cur.execute(self.query)

Then I construct the object as follows:

db_app = DbOperations()
db_app.db_connect()
db_app.db_create_table()

I am able to manually connect to the database and create the table. However, I'm not able to do so using Python. There are no exceptions or error messages. When I try to list the tables in the database manually, I don't find my newly created table. Any suggestions what could be wrong ?

3
  • So what went wrong?, Any error message to post that could help solving your case? :) Commented Jan 13, 2017 at 18:38
  • Eventually there are no exceptions or error messages. When I try to list the tables in the database manually, I don't find my newly created table Commented Jan 13, 2017 at 18:39
  • 2
    You should commit after execute :) Commented Jan 13, 2017 at 18:48

2 Answers 2

2

Seems, you are missing the commit at the end of db_create_table method:

self.conn.commit()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it worked. I was following Python's documentation for psycopg2 but it never mentioned so! weird
Can you post the link to it?
1

Iron Fist's answer is absolutely correct, but if you don't want to have commits all over your code, you can also set it on the connection like this:

def db_connect(self):
    self.conn = psycopg2.connect(dbname=self.db_name, user=self.user, password=self.password, host=self.host)
    self.conn.autocommit = True
    self.cur = self.conn.cursor()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.