首页 > 解决方案 > 在python中查询多个postgres表

问题描述

我正在尝试查询多个 sql 表并将它们存储为 pandas 数据框。

cur = conn.cursor()
  cur.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
  tables_df = cur.fetchall()
  ##table_name_list = tables_df.table_name 
  select_template = ' SELECT * FROM {table_name}'
  frames_dict = {}
  for tname in tables_df :
      query = select_template.format(table_name = tname)
      frames_dict [tname] = pd.read_sql ( query , conn)

但我收到如下错误:

 DatabaseError: Execution failed on sql ' SELECT * FROM ('customer',)': syntax 
 error at or near "'yesbank'"
`enter code here`LINE 1:  SELECT * FROM ('customer',)

客户是我从行获得的数据库中的表名

 tables_df = cur.fetchall()

标签: sqlpython-3.xpandaspostgresqlpsycopg2

解决方案


根据您的错误,看起来您的 word 格式有错字:

 AttributeError: 'str' object has no attribute 'formate'

尝试

query = select_template.format(table_name = tname)

推荐阅读