如何使用Psycopg2 Python库确定表是否存在?我想要一个真或假的布尔值。
答案 0 :(得分:66)
怎么样:
>>> 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
使用EXISTS的替代方案更好,因为它不需要检索所有行,而只需要存在至少一个这样的行:
>>> cur.execute("select exists(select * from information_schema.tables where table_name=%s)", ('mytable',))
>>> cur.fetchone()[0]
True
答案 1 :(得分:19)
我不知道具体的psycopg2 lib,但可以使用以下查询来检查表的存在:
SELECT EXISTS(SELECT 1 FROM information_schema.tables
WHERE table_catalog='DB_NAME' AND
table_schema='public' AND
table_name='TABLE_NAME');
使用information_schema而不是直接从pg_ *表中进行选择的优点是查询的某种程度的可移植性。
答案 2 :(得分:3)
select exists(select relname from pg_class
where relname = 'mytablename' and relkind='r');
答案 3 :(得分:2)
#!/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()
答案 4 :(得分:1)
第一个答案对我不起作用。我发现成功检查了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
答案 5 :(得分:1)
我知道您要提供psycopg2答案,但是我想我会添加一个基于pandas的实用程序功能(它在后台使用了psycopg2),只是因为pd.read_sql_query()
使事情变得如此便捷,例如避免创建/关闭游标。
import pandas as pd
def db_table_exists(conn, tablename):
# thanks to Peter Hansen's answer for this sql
sql = f"select * from information_schema.tables where table_name='{tablename}'"
# return results of sql query from conn as a pandas dataframe
results_df = pd.read_sql_query(sql, conn)
# True if we got any results back, False if we didn't
return bool(len(results_df))
与这里的其他答案类似,我仍然使用psycopg2创建数据库连接对象conn
。
答案 6 :(得分:0)
以下解决方案也在处理schema
:
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])
答案 7 :(得分:0)
扩展上面对EXISTS的使用,我需要一些东西来测试表的总体存在。我发现在select语句上使用访存测试结果会在空的现有表上产生结果“ None”-不理想。
这是我想出的:
import psycopg2
def exist_test(tabletotest):
schema=tabletotest.split('.')[0]
table=tabletotest.split('.')[1]
existtest="SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = '"+schema+"' AND table_name = '"+table+"' );"
print('existtest',existtest)
cur.execute(existtest) # assumes youve already got your connection and cursor established
# print('exists',cur.fetchall()[0])
return ur.fetchall()[0] # returns true/false depending on whether table exists
exist_test('someschema.sometable')