在Sagemaker Notebook中使用cursor.execute执行Snowflake查询时遇语法错误
问题解决:Snowflake查询在Jupyter/Sagemaker Notebook中触发语法错误
问题根源
你在Python代码中用双引号包裹SQL语句,但SQL条件里的"dsp"未做转义,Python会把"select ... '[后面的"当成字符串的结束符,导致后续内容被解析为无效语法。而Snowflake客户端直接执行SQL时无需考虑Python的字符串解析规则,所以能正常运行。
可行解决方案
给出三种解决方式,任选其一即可:
方案1:使用三引号包裹SQL语句
三引号(单/双均可)允许字符串内部包含未转义的单双引号,写法更简洁:
try: cs.execute("""select * FROM HEVOPROD_DB.HEVOPROD_SCH.PRDNEW_METERING where REQUESTED_SERVICE = '["dsp"]' and storeid is not null and latitude is not null and longitude is not null """) prev = time() for df in cs.fetch_pandas_batches(): print(time() - prev) print(df.shape) temp_all_dfs.append(df) prev = time() finally: cs.close() ctx.close()
方案2:转义SQL内部的双引号
在原有双引号包裹的SQL中,给内部的双引号添加反斜杠转义:
try: cs.execute("select * FROM HEVOPROD_DB.HEVOPROD_SCH.PRDNEW_METERING where REQUESTED_SERVICE = '[\"dsp\"]' and storeid is not null and latitude is not null and longitude is not null ") prev = time() for df in cs.fetch_pandas_batches(): print(time() - prev) print(df.shape) temp_all_dfs.append(df) prev = time() finally: cs.close() ctx.close()
方案3:用单引号包裹SQL,转义内部单引号
用单引号包裹整个SQL时,SQL里的单引号需要写成两个连续单引号来转义:
try: cs.execute('select * FROM HEVOPROD_DB.HEVOPROD_SCH.PRDNEW_METERING where REQUESTED_SERVICE = ''["dsp"]'' and storeid is not null and latitude is not null and longitude is not null ') prev = time() for df in cs.fetch_pandas_batches(): print(time() - prev) print(df.shape) temp_all_dfs.append(df) prev = time() finally: cs.close() ctx.close()
内容的提问来源于stack exchange,提问作者lifo
相关产品推荐
相关产品推荐

