簡體   English   中英

使用python測試postgresql數據庫時出錯

[英]Error while testing postgresql database with python

我想開始在python中使用數據庫。 我為數據庫“語言”選擇了postgresql。 我已經創建了幾個數據庫,但現在我只想檢查數據庫是否存在python。 為此,我已經閱讀了這個答案: 檢查python(可能是Psycopg2)下是否存在postgresql表並嘗試使用他們的解決方案:

import sys
import psycopg2

con = None

try:
    con = psycopg2.connect(database="testdb", user="test", password="abcd")
    cur = con.cursor()
    cur.execute("SELECT exists(SELECT * from information_schema.testdb)")
    ver = cur.fetchone()[0]
    print ver
except psycopg2.DatabaseError, e:
    print "Error %s" %e
    sys.exit(1)
finally:
    if con:
        con.close()

但不幸的是,我只得到輸出

Error relation "information_schema.testdb" does not exist
LINE 1: SELECT exists(SELECT * from information_schema.testdb)

我做錯了什么,還是我錯過了什么?

你的問題讓我感到困惑,因為你說你想查看數據庫是否存在,但你查看了information_schema.tables視圖。 該視圖將告訴您當前打開的數據庫中是否存在表。 如果要檢查數據庫是否存在,假設您可以訪問“postgres”數據庫,則可以:

import sys
import psycopg2, psycopg2.extras
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
dbname = 'db_to_check_for_existance'
con = None

try:
    con = psycopg2.connect(database="postgres", user="postgres")
    cur = con.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute("select * from pg_database where datname = %(dname)s", {'dname': dbname })
    answer = cur.fetchall()
    if len(answer) > 0:
        print "Database {} exists".format(dbname)
    else:
        print "Database {} does NOT exist".format(dbname)
except Exception, e:
    print "Error %s" %e
    sys.exit(1)
finally:
    if con:
        con.close()

這里發生的是您正在查找名為pg_database的數據庫表。 列'datname'包含每個數據庫名稱。 您的代碼將提供db_to_check_for_existance作為要檢查存在的數據庫的名稱。 例如,您可以用'postgres'替換該值,您將得到'exists'答案。 如果用aardvark替換該值,您可能會得到不存在的報告。

如果您正在嘗試查看數據庫是否存在:

curs.execute("SELECT exists(SELECT 1 from pg_catalog.pg_database where datname = %s)", ('mydb',))

聽起來你可能會對數據庫和表之間的區別感到困惑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM