使用 Python 将 CSV 文件导入 SQL Server

新手上路,请多包涵

我在将 CSV 文件上传到 MS SQL Server 中的表时遇到问题,CSV 文件有 25 列,标题与 SQL 中的表同名,后者也有 25 列。当我运行脚本时它抛出一个错误

params arg (<class 'list'>) can be only a tuple or a dictionary

将此数据导入 MS SQL 的最佳方法是什么? CSV 和 SQL 表都具有完全相同的列名。

这是代码:

 import csv
import pymssql

conn = pymssql.connect(
    server="xx.xxx.xx.90",
    port = 2433,
    user='SQLAdmin',
    password='xxxxxxxx',
    database='NasrWeb'
)

cursor = conn.cursor()
customer_data = csv.reader('cleanNVG.csv') #25 columns with same header as SQL

for row in customer_data:
    cursor.execute('INSERT INTO zzzOracle_Extract([Customer Name]\
      ,[Customer #]\
      ,[Account Name]\
      ,[Identifying Address Flag]\
      ,[Address1]\
      ,[Address2]\
      ,[Address3]\
      ,[Address4]\
      ,[City]\
      ,[County]\
      ,[State]\
      ,[Postal Code]\
      ,[Country]\
      ,[Category ]\
      ,[Class]\
      ,[Reference]\
      ,[Party Status]\
      ,[Address Status]\
      ,[Site Status]\
      ,[Ship To or Bill To]\
      ,[Default Warehouse]\
      ,[Default Order Type]\
      ,[Default Shipping Method]\
      ,[Optifacts Customer Number]\
      ,[Salesperson])''VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,)',row)

conn.commit()
cursor.close()
print("Done")
conn.close()

这是 CSV 文件的第一行的样子

在此处输入图像描述

原文由 Cesar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
1 个回答

尝试 d6tstack ,它具有 快速 pandas 到 SQL 的功能,因为它使用本机数据库导入命令。它适用于 Postgres 和 MYSQL,MS SQL 是实验性的。如果不起作用,请发表评论或提出问题。

 import pandas as pd
df = pd.read_csv('cleanNVG.csv')
uri_mssql = 'mssql+pymssql://usr:pwd@localhost/db'
d6tstack.utils.pd_to_mssql(df, uri_mssql, 'table', 'schema') # experimental

它对于导入多个 CSV 数据模式更改和/或在写入数据库之前使用 pandas 进行预处理也很有用,请参阅 示例笔记本

d6tstack.combine_csv.CombinerCSV(glob.glob('*.csv'),
    apply_after_read=apply_fun).to_mssql_combine(uri_psql, 'table')

原文由 citynorman 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏