首页 > 解决方案 > Python 将 CSV 导入 SQL Server

问题描述

我正在尝试使用 Python 将 CSV 文件插入 SQL Server Express。

我引用了 Importing a csv file into sql server using python但我仍然无法让它工作。我在 CSV 文件中有 24 个列名,数据库表已经在 SQL 中创建。表名是[dev].[dbo].[Cust]

这是我现在得到的错误

回溯(最后一次调用):
文件“C:\Test\Cust.py”,第 5 行,在
my_cursor = cnxn.cursor()
NameError: name 'cnxn' is not defined

列名是

Schedule Date, Schedule In, Schedule Out, Schedule Area, Cust/Non Cust, 
account, Account ID, Last Name, Company Abbr, Company Name, Account Code, 
ADT, Supervisor, position, Available Open Time, Events, 8 - 11 am, 11 - 2 pm, 
2 - 5 pm, 5 - 8 pm, 8 - 11 pm, All Day, Total available, Comment

任何帮助将不胜感激

import pyodbc
import csv

# DESTINATION CONNECTION
my_cursor = cnxn.cursor()
my_cnxn = pyodbc.connect('Driver=SQL Server;'
                      'Server=#######\SQLEXPRESS;'
                      'Database=DEV;'
                      'Trusted_Connection=yes;')
                      
print("Connected")

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 ({})' \
        .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()

table = 'Cust'
mycsv = 'C:\test\Cust.csv' # SET YOUR FILEPATH
insert_records(table, mycsv, my_cursor, my_cnxn)
cursor.close()

标签: pythonsql-servercsvinsert

解决方案


推荐阅读