Postgres Psycopg2 创建表

22

我是Postgres和Python的新手。我尝试创建一个简单的用户表,但不知道为什么它没有被创建。 错误信息没有出现,

    #!/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()

任何帮助或提示都将不胜感激。 谢谢。


数据库日志中没有错误信息吗? - Erik
1个回答

57

你忘记提交到数据库了!

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()

`


2
或者在连接之前使用 conn.autocommit = True 也可以完成工作。 - Andrew_Dublin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接