【发布时间】:2017-06-26 16:18:46
【问题描述】:
我正在尝试在 udacity 的关系数据库入门课程中做一个最终的“锦标赛”项目。这是项目描述的链接:
https://docs.google.com/document/d/16IgOm4XprTaKxAa8w02y028oBECOoB1EI1ReddADEeY/pub?embedded=true
我有一个名为tournament.sql 的文件,其中定义了数据库'tournament' 和两个表'matches' 和'players':
DROP DATABASE IF EXISTS tournament;
CREATE DATABASE tournament;
CREATE TABLE IF NOT EXISTS matches (
id SERIAL PRIMARY KEY,
player1 integer references players (id),
player2 integer references players (id)
);
CREATE TABLE IF NOT EXISTS players (
id SERIAL PRIMARY KEY,
name varchar(40)
);
我还在锦标赛.py 文件中定义了两个函数 deleteMatches 和 deletePlayers 的主体:
import psycopg2
def connect():
"""Connect to the PostgreSQL database. Returns a database connection."""
return psycopg2.connect("dbname=tournament")
def deleteMatches():
"""Remove all the match records from the database."""
conn = connect()
c = conn.cursor()
c.execute("TRUNCATE TABLE matches;")
conn.commit()
conn.close()
def deletePlayers():
"""Remove all the player records from the database."""
conn = connect()
c = conn.cursor()
c.execute("TRUNCATE TABLE players;")
conn.commit()
conn.close()
还有一个由整个课程“tournament_test.py”的作者预定义/预构建的python文件,可以执行该文件以检查tournament.py中所有必需的功能是否正常工作/完成他们的工作。该文件'tournament_test.py'是从命令行在虚拟机中执行的,在我的情况下会产生以下错误:
vagrant@vagrant-ubuntu-trusty-32:/vagrant/tournament$ python tournament_test.py
Traceback (most recent call last):
File "tournament_test.py", line 151, in
testCount()
File "tournament_test.py", line 17, in testCount
deleteMatches()
File "/vagrant/tournament/tournament.py", line 16, in deleteMatches
c.execute("TRUNCATE TABLE matches;")
psycopg2.ProgrammingError: relation "matches" does not exist
有人知道我的代码有什么问题吗?我开始失去耐心了。我花了几个小时试图找出问题所在,我可以找到任何有用的信息。这门课太糟糕了,草率且不专业。我就是找不到合适的词来表达我的沮丧。
【问题讨论】:
-
您是否将该 SQL 文件加载到数据库中?怎么样?
-
我不明白这个问题。将 SQL 文件加载到数据库中是什么意思?你说的是哪个数据库?我应该如何将 sql 文件加载到数据库中?你的意思是:“从锦标赛导入*”这是预定义的python文件锦标赛测试.py的顶部吗?
-
那么您希望文件自己做什么?编写一个 SQL 命令文件非常好,但除非你真的将它们提供给数据库,否则你还不如编写童谣。您的错误是告诉您您尚未创建表,如果您从未实际运行过该文件,这是正确的。
-
如果你的意思是将锦标赛.sql 加载到 psql 中:vagrant@vagrant-ubuntu-trusty-32:/vagrant/tournament$ psql
标签: python sql postgresql virtual-machine git-bash