我目前在使用前一个答案中使用的python编码的微小变体将csv文件导入sql时遇到问题: - Insert csv into sql database
我遇到了一个问题,我收到以下语法错误: -
line 28, in insert_records
cursor.execute(insert +'('+ ', '.join(values) +');')
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 13 for
SQL Server][SQL Server]Incorrect syntax near '/'. (102) (SQLExecDirectW)")
我相信我已经接近成功将此csv文件导入sql server。目前sql server标题中的表已经存在。我附加了我正在使用的python代码,程序终止于[cursor.execute(insert +'('+','。join(values)+');')]
提前致谢, 布赖恩
import pyodbc
import csv
print('connecting')
conn = pyodbc.connect(r'DRIVER={ODBC Driver 13 for SQL Server};'r'SERVER=.\SQLExpress;'r'DATABASE=UFOGBobservations;'r'Trusted_Connection=yes')
print('Connected')
my_cursor = conn.cursor()
print('Cursor established')
def insert_records(table, yourcsv, cursor, cnxn):
#INSERT SOURCE RECORDS TO DESTINATION
with open(yourcsv) as csvfile:
csvFile = csv.reader(csvfile, delimiter=',')
header = next(csvFile)
headers = map((lambda x: x.strip()), header)
insert = 'INSERT INTO {} ('.format(table) + ', '.join(headers) + ') VALUES '
for row in csvFile:
values = map((lambda x: "'"+x.strip()+"'"), row)
cursor.execute(insert +'('+ ', '.join(values) +');')
conn.commit() #must commit unless your sql database auto-commits
table = 'table_1'
mycsv = r'C:\DataAnalystData\UFOGB_Observations.csv' # SET YOUR FILEPATH
insert_records(table, mycsv, my_cursor, conn)
cursor.close()
答案 0 :(得分:0)
这可能是一个逃避问题。如果将值作为参数列表传递给execute()
而不是手动构建字符串,则会更安全。这将确保它们被正确转义。
insert = 'INSERT INTO {} ('.format(table) + ', '.join(headers) + ') VALUES ({})' \
.format(', '.join(len(headers) * '?')) # Add parameter placeholders as ?
for row in csvFile:
values = map((lambda x: x.strip()), row) # No need for the quotes
cursor.execute(insert, values) # Pass the list of values as 2nd argument
conn.commit()