2009-12-09 31 views

Trả lời

56

Làm thế nào về:

>>> import psycopg2 
>>> conn = psycopg2.connect("dbname='mydb' user='username' host='localhost' password='foobar'") 
>>> cur = conn.cursor() 
>>> cur.execute("select * from information_schema.tables where table_name=%s", ('mytable',)) 
>>> bool(cur.rowcount) 
True 

Một thay thế sử dụng EXISTS là tốt hơn ở chỗ nó không đòi hỏi rằng tất cả các hàng được lấy ra, nhưng chỉ đơn thuần là ít nhất một dòng như vậy tồn tại:

>>> cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',)) 
>>> cur.fetchone()[0] 
True 
+2

Đóng nhưng tốt hơn để sử dụng 'exist()'. :) – jathanism

+2

Tôi đã thêm rằng, nhưng tại sao nó "tốt hơn"? –

+2

@Peter Nó là tốt hơn bởi vì nó chỉ cần tìm hàng đầu tiên phù hợp với điều kiện 'where' trong khi' rowcount' sẽ phải lấy tất cả các hàng. –

3
select exists(select relname from pg_class 
where relname = 'mytablename' and relkind='r'); 
+0

không hoạt động cho relname với lược đồ, như 'myschema.tabname' –

19

Tôi không biết các lib psycopg2 cụ thể, nhưng với câu truy vấn sau đây có thể được sử dụng để kiểm tra sự tồn tại của một bảng:

SELECT EXISTS(SELECT 1 FROM information_schema.tables 
       WHERE table_catalog='DB_NAME' AND 
        table_schema='public' AND 
        table_name='TABLE_NAME'); 

Ưu điểm của việc sử dụng information_schema qua chọn trực tiếp từ pg_ * bảng là một mức độ di động của truy vấn.

+0

Đối mặc định table_catalog sử dụng ?? –

1

Câu trả lời đầu tiên không hiệu quả với tôi. Tôi tìm thấy thành công kiểm tra các mối quan hệ trong pg_class:

def table_exists(con, table_str): 
    exists = False 
    try: 
     cur = con.cursor() 
     cur.execute("select exists(select relname from pg_class where relname='" + table_str + "')") 
     exists = cur.fetchone()[0] 
     print exists 
     cur.close() 
    except psycopg2.Error as e: 
     print e 
    return exists 
1
#!/usr/bin/python 
# -*- coding: utf-8 -*- 

import psycopg2 
import sys 


con = None 

try: 

    con = psycopg2.connect(database='testdb', user='janbodnar') 
    cur = con.cursor() 
    cur.execute('SELECT 1 from mytable')   
    ver = cur.fetchone() 
    print ver //здесь наш код при успехе 


except psycopg2.DatabaseError, e: 
    print 'Error %s' % e  
    sys.exit(1) 


finally: 

    if con: 
     con.close() 
0

Các giải pháp sau đây là xử lý các schema quá:

import psycopg2 

with psycopg2.connect("dbname='dbname' user='user' host='host' port='port' password='password'") as conn: 
    cur = conn.cursor() 
    query = "select to_regclass(%s)" 
    cur.execute(query, ['{}.{}'.format('schema', 'table')]) 

exists = bool(cur.fetchone()[0]) 
Các vấn đề liên quan