Ricardo Pinto
Ricardo Pinto

Reputation: 373

Postgres Psycopg2 Create Table

I am new to Postgres and Python. I try to create a simple user table but I don't know why it isn't created. The error message doesn't appear,

    #!/usr/bin/python
    import psycopg2
    
    try:
        conn = psycopg2.connect(database = "projetofinal", user = "postgres", password = "admin", host = "localhost", port = "5432")
    except:
        print("I am unable to connect to the database") 
    
    cur = conn.cursor()
    try:
        cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
    except:
        print("I can't drop our test database!")
    
    conn.close()
    cur.close()

Any help or hint would be appreciated. Thank you.

Upvotes: 24

Views: 37655

Answers (1)

Matt
Matt

Reputation: 1135

You are forgetting to commit to the database!

import psycopg2

try:
    conn = psycopg2.connect(database = "projetofinal", user = "postgres", password = "admin", host = "localhost", port = "5432")
except:
    print("I am unable to connect to the database") 

cur = conn.cursor()
try:
    cur.execute("CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);")
except:
    print("I can't drop our test database!")

conn.commit() # <--- makes sure the change is shown in the database
conn.close()
cur.close()

`

Upvotes: 59

Related Questions