python读写csv与数据库性能,使用python将CSV文件写入SQL Server数据库

Hi I am trying to write a csv file into a table in SQL Server database using python. I am facing errors when I pass the parameters , but I don't face any error when I do it manually. Here is the code I am executing.

cur=cnxn.cursor() # Get the cursor

csv_data = csv.reader(file(Samplefile.csv')) # Read the csv

for rows in csv_data: # Iterate through csv

cur.execute("INSERT INTO MyTable(Col1,Col2,Col3,Col4) VALUES (?,?,?,?)",rows)

cnxn.commit()

Error :pyodbc.DataError: ('22001', '[22001] [Microsoft][ODBC SQL Server Driver][SQL Server]String or binary data would be truncated. (8152) (SQLExecDirectW); [01000] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been terminated. (3621)')

However when I insert the values manually. It works fine

cur.execute("INSERT INTO MyTable(Col1,Col2,Col3,Col4) VALUES (?,?,?,?)",'A','B','C','D')

I have ensured that the TABLE is there in the database, data types are consistent with the data I am passing. Connection and cursor are also correct. The data type of rows is "list"

解决方案

Consider building the query dynamically to ensure the number of placeholders matches your table and CSV file format. Then it's just a matter of ensuring your table and CSV file are correct, instead of checking that you typed enough ? placeholders in your code.

The following example assumes

CSV file contains column names in the first line

Connection is already built

File name is test.csv

Table name is MyTable

Python 3

...

with open ('test.csv', 'r') as f:

reader = csv.reader(f)

columns = next(reader)

query = 'insert into MyTable({0}) values ({1})'

query = query.format(','.join(columns), ','.join('?' * len(columns)))

cursor = connection.cursor()

for data in reader:

cursor.execute(query, data)

cursor.commit()

If column names are not included in the file:

...

with open ('test.csv', 'r') as f:

reader = csv.reader(f)

data = next(reader)

query = 'insert into MyTable values ({0})'

query = query.format(','.join('?' * len(data)))

cursor = connection.cursor()

cursor.execute(query, data)

for data in reader:

cursor.execute(query, data)

cursor.commit()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值