python - 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()
解决方案
推荐阅读
- .net-core - 在开发过程中伪造身份验证
- tensorflow - Tensorflow 未显示正确的可用内存量
- machine-learning - 为什么以及何时需要深度强化学习而不是 q-learning?
- c# - 使用 System.Web.Mvc.RouteAttribute 时 ActionLink 构建错误的 URL
- ms-word - 在 Word Office JS 中隐藏内容控件
- javascript - 如何使用php将xml子元素添加到数组的第一个索引
- android - PackageManager.getInstalledApplications(0); 在安卓 7.0 中
- c# - 在 TextChanged 上动态创建 TextBox AutoPostBack 但未调用事件函数
- excel - 打印 PDF 期间出现 VBA 错误 1004
- html - XHR 适用于 localhost 服务器,但不适用于我在 IIS 上的静态 IP