Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中执行创建表的Postgresql查询_Python_Postgresql - Fatal编程技术网

在Python中执行创建表的Postgresql查询

在Python中执行创建表的Postgresql查询,python,postgresql,Python,Postgresql,我正在创建一个Flask webapp,它显示各种Postgresql查询的结果。作为初始化的一部分,我希望运行一个查询,在Postgresql中创建一个表,其中包含后续查询所需的所有数据。我的问题是,尽管webapp似乎初始化正确(因为它不会抛出任何异常),但我不知道新表存储在哪里(我相信我已经正确地给它命名了),并且我无法从任何其他查询访问它 代码如下: import psycopg2 as p2 import pandas conn = p2.connect("dbname='x' us

我正在创建一个Flask webapp,它显示各种Postgresql查询的结果。作为初始化的一部分,我希望运行一个查询,在Postgresql中创建一个表,其中包含后续查询所需的所有数据。我的问题是,尽管webapp似乎初始化正确(因为它不会抛出任何异常),但我不知道新表存储在哪里(我相信我已经正确地给它命名了),并且我无法从任何其他查询访问它

代码如下:

import psycopg2 as p2
import pandas

conn = p2.connect("dbname='x' user='y' host='z' password='password' port='1234'")
cur = conn.cursor()

def exec_postgres_file(cursor, postgres_file):
    statement = open(postgres_file).read()
    try:
        cursor.execute(statement)
    except (p2.OperationalError, p2.ProgrammingError) as e:
        print "\n[WARN] Error during execute statement \n\tArgs: '%s'" % (str(e.args))

exec_postgres_file(cur,'/Filepath/initialization_query.sql')
cur.execute("""SELECT * FROM schema.new_table""")
rows = cur.fetchall()
new_table_df = pandas.DataFrame(rows)
print new_table_df

exec_postgres_file(cur,'/Filepath/query1.sql')
rows2 = cur.fetchall()
query1_df = pandas.DataFrame(rows2)
print query1_df
其中new_table是在初始化_查询期间创建的表。query1正在尝试访问新表,但在第二条exec\U postgres\U file语句后引发异常:

第10行不存在关系“新建表格”

假设初始化查询为:

select *
into schema.new_table
from schema.old_table
where id in    ('A','B','C','D','E','F')
;
问题1是:

select date, sum(revenue) as revenue  
from schema.new_table
group by date
;

当我在像Navicat这样的数据库管理工具中运行查询时,这两种方法都能起作用。

这就是Flask Migrate的目的:

请发布创建代码和访问代码。为什么要在exec\u postgres\u文件中捕获异常?最好让它们“冒泡”,并通过适当的回溯使整个过程快速失败,而不是试图继续下去(并让它在以后失败。)顺便说一句,这将有助于了解如何查看
初始化\u query.sql
文件的内容。。我猜你的查询有问题。解决了-我没有将初始事务提交到后端。