根据Unload to S3 with Python using IAM Role credentials,卸载语句完美无缺。我尝试过的其他命令也是如此,例如copy和select语句。
但是,我还尝试运行一个创建表的查询。创建表查询运行时没有错误,但是当它到达select语句时,它会抛出relation "public.test" does not exist
的错误。
知道为什么桌子没有正确创建?查询如下:
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker
import config
import pandas as pd
#>>>>>>>> MAKE CHANGES HERE >>>>>>>>
DATABASE = "db"
USER = "user"
PASSWORD = getattr(config, 'password') #see answer by David Bern https://stackoverflow.com/questions/43136925/create-a-config-file-to-hold-values-like-username-password-url-in-python-behave/43137301
HOST = "host"
PORT = "5439"
SCHEMA = "public" #default is "public"
########## connection and session creation ##########
connection_string = "redshift+psycopg2://%s:%s@%s:%s/%s" % (USER,PASSWORD,HOST,str(PORT),DATABASE)
engine = sa.create_engine(connection_string)
session = sessionmaker()
session.configure(bind=engine)
s = session()
SetPath = "SET search_path TO %s" % SCHEMA
s.execute(SetPath)
--create table example
query2 = '''\
create table public.test (
id integer encode lzo,
user_id integer encode lzo,
created_at timestamp encode delta32k,
updated_at timestamp encode delta32k
)
distkey(id)
sortkey(id)
'''
r2 = s.execute(query2)
--select example
query4 = '''\
select * from public.test
'''
r4 = s.execute(query4)
########## create DataFrame from SQL query output ##########
df = pd.read_sql_query(query4, connection_string)
print(df.head(50))
########## close session in the end ##########
s.close()
如果我在Redshift中直接运行它,它可以正常工作..
- 编辑 -
尝试了一些事情:
删除" \"来自查询字符串
添加";"在查询字符串
改变" public.test"到"测试"
删除SetPath =" SET search_path TO%s" %SCHEMA和s.execute(SetPath)
打破create语句 - 生成预期错误
创建运行后从S3命令添加副本没有错误,但同样没有创建表
添加列以创建在复制命令生成的文件中不存在的语句 - 生成预期错误
添加r4 = s.execute(query4) - 运行没有错误,但是再次创建的表不在Redshift中
答案 0 :(得分:2)
显然需要添加s.commit()才能创建表..如果您通过复制命令填充它或插入到:然后在复制命令之后添加它(在create table是可选的之后)。基本上,它不会自动提交create / alter命令!
http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#session-faq-whentocreate http://docs.sqlalchemy.org/en/latest/core/connections.html#understanding-autocommit