소개 : 저는 Udacity에서 Relational Database 과정을 위해 Ubuntu VM을 실행하는 Vagrant를 사용하여 스위스 스타일의 PostgreSQL 데이터베이스를 구축했습니다.psycopg2.ProgrammingError를 반환하는 파이썬 지원 SQL 데이터베이스 : 테이블 내에있는 데이터를 삭제하려고 할 때 관계가 존재하지 않습니다 오류가 발생 했습니까?
질문 : 기존 표의 정보를 삭제하려고 시도하면 표가 존재하지 않는 이유는 무엇입니까?
나는psycopg2.ProgrammingError
조회 일반적인 검색을했지만이 정보는 다른 상황에 주로 특정, 나는 나에게이 문제를 해결할 수있는 것이 논리적 연결을 할 수 없습니다. 또한 동일한 문제가있는
other thread here에 가까운 다른 스택 오버플로 스레드가 발견되었지만 해결되지 않았습니다. 그래서 나는이 질문을 만들어 내 수수께끼를 이해할 수있는 사람을 찾고 나와 올바른 방향으로 일하기위한 암시 또는 단서를 제공합니다.
토너먼트 데이터베이스 SQL 파일을 Vagrant VM으로 가져 왔습니다. 이렇게하면 두 테이블 (플레이어와 일치)과 데이터베이스 (토너먼트)가 삭제 된 후이 데이터베이스와 테이블이 다시 만들어집니다. 그래서 테이블 (일치)이 있다는 것을 압니다. (현재 방랑 오류)
[email protected]:/vagrant/tournament$ python tournament_test.py
Traceback (most recent call last):
File "tournament_test.py", line 151, in <module>
testCount()
File "tournament_test.py", line 17, in testCount
deleteMatches()
File "/vagrant/tournament/tournament.py", line 18, in deleteMatches
cursor.execute("DELETE FROM matches;")
psycopg2.ProgrammingError: relation "matches" does not exist
LINE 1: DELETE FROM matches;
^
SQL : 그러나,이 내가 ...
방랑을 얻고 무엇을 (tournament.sql의 모든)
-- Table definitions for the tournament project.
--
-- Put your SQL 'create table' statements in this file; also 'create view'
-- statements if you choose to use it.
--
-- You can write comments in this file by starting them with two dashes,
like
-- these lines here.
DROP TABLE matches;
DROP TABLE players;
DROP DATABASE tournament;
CREATE DATABASE tournament;
CREATE TABLE players (player_id SERIAL UNIQUE PRIMARY KEY, name
VARCHAR(40));
CREATE TABLE matches (match_id SERIAL UNIQUE PRIMARY KEY,
winner INTEGER REFERENCES players(player_id),
loser INTEGER REFERENCES players (player_id));
파이썬 (에서 최소 tournament.py)
는#!/usr/bin/env python
#
# tournament.py -- implementation of a Swiss-system tournament
#
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."""
db = connect()
cursor = db.cursor()
cursor.execute("TRUNCATE matches CASCADE;")
db.commit()
db.close()
파이썬이는 tournament.py을 확인하는 파일) tournament_test.py에서 (최소한의 함수는 tournament.sql 데이터베이스로 작업합니다.
#!/usr/bin/env python
#
# Test cases for tournament.py
from tournament import *
def testCount():
"""
Test for initial player count,
player count after 1 and 2 players registered,
player count after players deleted.
"""
deleteMatches()
deletePlayers()
c = countPlayers()
if c == '0':
raise TypeError(
"countPlayers should return numeric zero, not string '0'.")
if c != 0:
raise ValueError("After deletion, countPlayers should return zero.")
print "1. countPlayers() returns 0 after initial deletePlayers()
execution."
registerPlayer("Chandra Nalaar")
c = countPlayers()
if c != 1:
raise ValueError(
"After one player registers, countPlayers() should be 1. Got
{c}".format(c=c))
print "2. countPlayers() returns 1 after one player is registered."
registerPlayer("Jace Beleren")
c = countPlayers()
if c != 2:
raise ValueError(
"After two players register, countPlayers() should be 2. Got
{c}".format(c=c))
print "3. countPlayers() returns 2 after two players are registered."
deletePlayers()
c = countPlayers()
if c != 0:
raise ValueError(
"After deletion, countPlayers should return zero.")
print "4. countPlayers() returns zero after registered players are
deleted.\n5. Player records successfully deleted."
testCount()
방랑은 (테이블 '일치'가 데이터베이스에 존재하는지 확인) :
이vagrant=> \dt
List of relations
Schema | Name | Type | Owner
--------+---------+-------+---------
public | matches | table | vagrant
public | players | table | vagrant
(2 rows)
갱신 2 : 명확한 설명이 내 파이썬 파일의 시작 부분에있는 DB에 연결
을 언급 .
def connect()
"""Connect to the PostgreSQL database. Returns a database
connection."""
return psycopg2.connect("dbname=tournament")
어떻게 DB에 연결합니까? –
안녕하세요. 그것은 많은 유용한 정보입니다. [mcve]에 대해서도 읽고 읽으십시오. 또한, 당신은 오류 메시지를 검색하여 배운 당신의 특정 테이블/열/제약/등 이름을? 댓글이 아닌 질문에 대한 설명을 수정하십시오. 업데이트를 단편적으로 추가하는 것이 아니라 귀하의 질문을 최신 상태로 유지하십시오. (이전 버전은 '수정'링크를 통해 액세스 할 수 있습니다.) – philipxy
감사합니다. [mcve]는 최소한의 발췌가 아니며 최소한의 발췌가 아닙니다. (또한 edit2는 질문에 이미있는 텍스트를 재생산합니다.) 문제를 나타내는 최소한의 코드가 포함 된 적절한 소프트웨어 (python/vagrant/postgresql)를 설치 한 사람이 편집하지 않고 실행할 수있는 스크립트를 포함한 전체 파일을 의미합니다. 그러한 파일에서 "발췌"하지 않습니다. 또한 tournament_test.py에서 deleteMatches를 호출 할 때 실행이 중지되면 해당 파일의 이후 코드가 실행되지 않는 이유는 무엇입니까? 추 신 : 귀하의 방글리데타 오류가 "DELETE FROM matches; tournament.py는 ""TRUNCATE가 캐스케이드와 일치합니다 "; – philipxy