如果db.table存在,我正在尝试从db.table中全选。我已经尝试过,如果存在,等等,都没有用。最好的方法是什么?我正在使用cockroachdb和psycopg2。找不到现有答案(大多数答案已经很旧了) 我可以使用的。例如,这对我没有用:SQl select all if table exists
我按照蒂姆的建议尝试了以下方法,但似乎不起作用。但是,db.table存在。
select exists (select 1 from information_schema.tables where table_name = 'table') ;
exists
+--------+
false
(1 row)
Time: 6.848579ms
select exists (select 1 from information_schema.tables where table_name = 'db.table') ;
exists
+--------+
false
(1 row)
Time: 5.958707ms
答案 0 :(得分:2)
您可以分两个步骤进行处理。首先,检查表是否存在于Postgres数据库中,如果存在,则选择所有记录:
sql = "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = %s"
cur.execute(sql, ('your_table',))
if cur.fetchone()[0]:
sql_all = "SELECT * FROM your_table"
cur = connection.cursor() # get a new cursor
cur.execute(sql_all)
# process result set etc.