Lambda中psycopg2 mogrify生成SQL多添单引号致Redshift插入失败
解决Redshift插入时单引号转义导致的语法错误问题
问题根源
你用psycopg2.mogrify生成的是PostgreSQL风格的单引号转义(把Abc's处理为'Abc''s'),但直接将这些片段拼接成完整SQL语句执行时,Redshift的SQL解析会错误识别转义后的单引号,导致语法错误。此外,手动拼接SQL本身就存在转义处理不当和SQL注入风险。
推荐解决方案:使用参数化批量插入
最安全可靠的方式是避免手动拼接SQL,改用psycopg2.extras.execute_values实现批量参数化插入,驱动会自动处理所有转义逻辑:
from psycopg2.extras import execute_values # 读取RDS数据的逻辑保持不变 query_rds_source = 'Select id, col1 from tbl1;' RDS_conn = psycopg2.connect( database=RDS_dbname, user=uname_PostgreSQL, password=password_PostgreSQL, host=host_PostgreSQL, port=port_PostgreSQL ) RDS_conn.autocommit = True RDS_cursor = RDS_conn.cursor() RDS_cursor.execute(query_rds_source) row_source = RDS_cursor.fetchall() # Redshift批量插入:使用execute_values替代手动拼接 insert_query = f'Insert into public.{redshift_stg_ups_tbl} (id, col1) values %s' # 直接传入查询语句和数据列表,驱动自动处理转义 execute_values(Redshift_cursor, insert_query, row_source) Redshift_conn.commit()
备选方案:调整转义格式(不推荐)
如果因特殊原因必须使用mogrify生成SQL片段,可以将PostgreSQL风格的双单引号替换为Redshift兼容的转义单引号,但这种方式容易引入其他转义问题,仅作为临时 workaround:
# 生成SQL片段时替换双单引号为转义单引号 args_str = ','.join( RDS_cursor.mogrify("(%s,%s)", x).decode('utf-8').replace("''", "\\'") for x in row_source ) insert_query = f'Insert into public.{redshift_stg_ups_tbl} (id, col1) values {args_str}' Redshift_cursor.execute(insert_query) Redshift_conn.commit()
内容的提问来源于stack exchange,提问作者Bhushan
相关产品推荐
相关产品推荐

