You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解决Vertica插入语句单引号转义及列数不匹配问题

解决Google Sheet数据推送Vertica的两个常见问题:列数不匹配与单引号语法错误

一、「插入语句列数不匹配」错误排查

  • 核对Google Sheet数据源的字段数量与Vertica目标表的列数,包括隐藏列、末尾空列都要统计在内
  • 检查INSERT语句的列清单(如INSERT INTO table(col1, col2))和VALUES子句里的字段数量是否严格一一对应,避免漏写、多写列名或值
  • 检查数据中是否存在换行、特殊分隔符,导致字段被意外拆分,引发列数统计错误

二、单引号语法问题的处理

你提到的将单引号替换为双单引号(如Samsung's → Samsung''s)是可行的,这是SQL中转义单引号的标准方式。不过更推荐使用参数化查询,既能避免单引号问题,还能防范SQL注入,代码更健壮。

方法1:循环替换单引号(满足你的需求)

import vertica_python

# 假设从Google Sheet获取的数据是一个二维列表
sheet_data = [["Samsung's Galaxy", 1200], ["Apple's iPhone", 1500]]

# 处理单引号:遍历每个字段替换
processed_data = []
for row in sheet_data:
    processed_row = []
    for item in row:
        if isinstance(item, str):
            # 替换单引号为双单引号
            processed_item = item.replace("'", "''")
            processed_row.append(processed_item)
        else:
            processed_row.append(item)
    processed_data.append(processed_row)

# 连接Vertica并插入数据
conn_info = {
    'host': 'your_vertica_host',
    'port': 5433,
    'user': 'your_user',
    'password': 'your_password',
    'database': 'your_db',
}

with vertica_python.connect(**conn_info) as conn:
    cur = conn.cursor()
    # 假设目标表有name和price两列
    insert_sql = "INSERT INTO products(name, price) VALUES ('%s', %s)"
    for row in processed_data:
        cur.execute(insert_sql % tuple(row))
    conn.commit()

方法2:参数化查询(更安全推荐)

import vertica_python

sheet_data = [["Samsung's Galaxy", 1200], ["Apple's iPhone", 1500]]

conn_info = {
    'host': 'your_vertica_host',
    'port': 5433,
    'user': 'your_user',
    'password': 'your_password',
    'database': 'your_db',
}

with vertica_python.connect(**conn_info) as conn:
    cur = conn.cursor()
    # 使用%s作为占位符,无需手动转义
    insert_sql = "INSERT INTO products(name, price) VALUES (%s, %s)"
    # 批量插入效率更高
    cur.executemany(insert_sql, sheet_data)
    conn.commit()

内容的提问来源于stack exchange,提问作者SQLLER

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 04:28:13