在insert语句中使用python中的值之间替换单个

vm0i2vca  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(148)

我试图从谷歌工作表数据推到数据库,但得到错误比插入语句更多的列。

import vertica_python
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import gspread.utils
#from utils import gspread.utils.batch_clear
#utils.path.insert(0, 'C:\\\Python311\\\Lib\\\site-packages\\\gspread\\\')

# Set up Google Sheets API credentials
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/spreadsheets']
creds = ServiceAccountCredentials.from_json_keyfile_name('cred.json', scope)
client = gspread.authorize(creds)

# Connect to Vertica database
conn_info = {
    'host': 'host',
    'port': 5433,
    'user': 'user',
    'password': 'password',
    'database': 'db'
}
connection = vertica_python.connect(**conn_info)
cursor = connection.cursor()

# Specify Google Sheet details
spreadsheet_key = 'spreadsheet_ID'
worksheet_name = 'Sheet1'
print('open')
# Retrieve data from Google Sheet
sheet = client.open_by_key(spreadsheet_key)
worksheet = sheet.worksheet(worksheet_name)
data = worksheet.get_all_values()
print('Close')
# Prepare and execute SQL statements to insert data into Vertica
columns = data[0]  # Assumes the first row contains column names
insert_statement = "INSERT INTO table ({}) VALUES ({})"
for row in data[1:]:  # Skip the first row (column names)
    values = "', '".join(row)  # Assumes values are strings
    insert_query = insert_statement.format(', '.join(columns), "'" + values + "'")
    # print(n +' '+insert_query)
    cursor.execute(insert_query)

# Commit changes and close connections
connection.commit()
cursor.close()
connection.close()

输入:insert into table(col1,col2,col2) values('Apple','Samsung's','nine')
三星的是造成一个问题,我们可以取代它像三星的在脚本中的for循环?

svmlkihl

svmlkihl1#

所以你可以在代码中转义',用''替换它们:

insert_statement = "INSERT INTO table ({}) VALUES ({})"
for row in data[1:]:  # Skip the first row (column names)
    values = "', '".join([item.replace("'", "''") for item in row]) # Assumes values are strings
    insert_query = insert_statement.format(', '.join(columns), "'" + values + "'")
    # print(n +' '+insert_query)
    cursor.execute(insert_query)

相关问题