使用python将csv文件导入sql server

时间:2021-11-21 23:53:57

I'm currently experiencing a problem importing a csv file to sql using a minor variation of python coding used in a previous answer:- Insert csv into sql database

我目前在使用前一个答案中使用的python编码的微小变体将csv文件导入sql时遇到问题: - 将csv插入sql数据库

I've run into an issue where I get the following syntax error:-

我遇到了一个问题,我得到以下语法错误: -

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)")

I believe I am close to succeeding into getting this csv file to import into sql server. Currently the table in sql server headings already present. I've attached the python code I am using, the program terminates at [cursor.execute(insert +'('+ ', '.join(values) +');')]

我相信我已经接近成功将这个csv文件导入到sql server中。目前sql server标题中的表已经存在。我附加了我正在使用的python代码,程序终止于[cursor.execute(insert +'('+','。join(values)+');')]

Thanks in advance, Bryan

谢谢,布莱恩

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()

1 个解决方案

#1


0  

This is possibly an escaping issue. It would be safer if you passed the values as a list of parameters to execute() rather than manually building a string. This will ensure that they are correctly escaped.

这可能是一个逃避问题。如果将值作为参数列表传递给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()

#1


0  

This is possibly an escaping issue. It would be safer if you passed the values as a list of parameters to execute() rather than manually building a string. This will ensure that they are correctly escaped.

这可能是一个逃避问题。如果将值作为参数列表传递给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()