Postgres Psycopg2创建选项卡

2024-05-20 12:11:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: to用户testclosebinusrconnectpostgres
1条回答
网友
1楼 · 发布于 2024-05-20 12:11:41

你忘了提交数据库!

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

`

相关问题 更多 >