问题描述
我正在尝试使用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:名称“ cnxn”未定义
列名是
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()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)