I am trying to insert a CSV file into SQL Server Express using Python.
I referenced Importing a csv file into sql server using python but I still can't get it to work. I have 24 column names in the CSV file, the database table is already created in SQL. The table name is [dev].[dbo].[Cust]
.
This is the error I am getting now
Traceback (most recent call last):
File "C:\Test\Cust.py", line 5, in
my_cursor = cnxn.cursor()
NameError: name 'cnxn' is not defined
Column names are
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
Any help would be greatly appreciated
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()