使用SQLAlchemy查询Snowflake表时遭遇SQL编译错误求助
解决Snowflake SQLAlchemy反射表时的路径错误问题
问题本质
错误提示Must specify the full search path starting from database for TPCH_SF1,是因为SQLAlchemy反射表时,无法通过当前会话上下文确定TPCH_SF1模式所属的数据库,必须明确指定完整对象路径,或确保会话搜索路径包含数据库与模式。
解决方案
方案1:反射表时使用数据库.模式完整路径
修改反射表的代码,将schema参数改为包含数据库名的完整路径:
# Reflect the table from the database table = Table('ORDERS', metadata, autoload_with=engine, schema='SNOWFLAKE_SAMPLE_DATA.TPCH_SF1')
方案2:会话中同时设置数据库和模式
在执行use database后,追加设置模式的命令,确保会话搜索路径覆盖模式:
# Set Database and Schema for session session.execute(text('use database SNOWFLAKE_SAMPLE_DATA')) session.execute(text('use schema TPCH_SF1')) # Reflect the table from the database table = Table('ORDERS', metadata, autoload_with=engine, schema='TPCH_SF1')
方案3:创建引擎时直接指定数据库和模式
修改create_engine的URL,直接嵌入数据库和模式信息,无需在会话中执行use命令:
engine = create_engine( 'snowflake://{user}:{password}@{account_identifier}/?database=SNOWFLAKE_SAMPLE_DATA&schema=TPCH_SF1'.format( user="", password="", account_identifier="" ) )
后续反射表可简化为:
table = Table('ORDERS', metadata, autoload_with=engine)
验证
修改后重新执行代码,即可正常反射ORDERS表并执行查询。
内容的提问来源于stack exchange,提问作者John Eipe
相关产品推荐
相关产品推荐

