postgresql Postgres Psycopg2 创建表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50070877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:42:46 来源:igfitidea点击:
Postgres Psycopg2 Create Table
提问by Ricardo Pinto
i′m new to Postgres and Python. I′m trying to create a simple user table but i don′t know why it isn′t creating. The error message doesn′t appear,
我是 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()
回答by Matt
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()
`
`